effective c++ 条款05:了解C++默默编写并调用哪些函数

记住:
如果没有声明任何构造函数,编译器会声明一个默认构造函数。
如果自己没有声明,编译器会声明一个拷贝构造函数,一个赋值操作符和一个析构函数。

class Empty {};

//编译器会声明默认的一些函数
class Empty {
public:
    Empty() { ... }
    Empty(const Empty& rhs) { ... }
    ~Empty() { ... }

    Empty& operator=(const Empty& rhs) { ... }
};
template<class T>
class NameObject {
public:
    NamedObject(string& name, const T& value);

private:
    string& nameValue;
    const T objectValue;
};

string newDog("pers");
string oldDog("satch");
NameObject<int> p(newDog, 2);
NameObject<int> s(oldDog, 36);

p = s; //调用赋值操作符,类中没有定义,那编译器能生成一个么?

不能。
对于内含引用成员的类,必须自己定义赋值操作符。 
更改const成员是不合法的。
另外,如果父类将copy assignment操作符声明为private,编译器也不会为它子类生成一个copy assignment操作符。

猜你喜欢

转载自www.cnblogs.com/pfsi/p/9160905.html