默认函数
当你写了一个空的class时, 尽管你并没有声明构造函数和析构函数, 编译器还是帮你生成了。
例如你写了一下代码定义了一个空的class:
class Empty {}:
在经过编译器的处理之后, 实际等于如下代码:
class Empty
{
public:
Empty(){}
~Empty(){}
Empty(const Emtpy& rhs){}
Empty& opreator=(const Empty& rhs) {}
};
编译器为你自动生成了构造函数,析构函数, 拷贝构造函数并且重载了=
运算符。
template<typename T>
class NameObject
{
public:
NameObject(const char* name, const T& value);
NameObjcet(const std::string& name, const T& value);
...
private:
std::string nameValue;
T ojbectValue;
};
在这个模板类中, 由于你已经声明了带参数的构造函数, 所以编译器不会为你生成无参数的构造函数, 而你并没有声明构造函数和=
, 编译器会帮你做这些事。
例外情况
试着考虑:
template<typename T>
class NameObject
{
public:
NameObjcet(const std::string& name, const T& value);
...
private:
std::string& nameValue;
const T ojbectValue;
};
std::string newDog("Persephone");
std::string oldDog("Satch");
NameObject<int> p(newDog, 2);
NameObject<int> s(oldDog, 2);
p = s;
在上述代码中, 当我们做最后的赋值时, 由于nameValue
是一个引用而objectValue
是一个常量,都不能赋予新值, 此时编译器就会拒绝生成默认的拷贝运算符,因为此时编译器不知道如何处理。