effective c++条款05

编译器可以暗自为class创建default构造函数,copy构造函数,copy assignment函数

看个例子

#include <Windows.h>
#include <iostream>
#include <string>
using namespace std;

class E05
{
    friend ostream& operator<<(ostream& out, E05& e05)
    {
        out << e05.m_name << " " << e05.m_age;
        return out;
    }
public:
    E05() {}
    E05(string name, int age) :m_name(name), m_age(age){}
    ~E05(){}
private:
    string m_name;
    int m_age;
};

int main()
{
    E05 e05_f("小明", 20);
    cout << e05_f << endl;
    E05 e05_s(e05_f);//使用了默认复制构造函数
    cout << e05_s << endl;
    E05 e05_t;
    e05_t = e05_f;//使用默认赋值构造函数
    cout << e05_t << endl;
    system("pause");
    return 0;
}

小明 20
小明 20
小明 20
这就是默认复制和赋值构造函数的效果

但是假如E05类是这样的

class E05
{
    friend ostream& operator<<(ostream& out, E05& e05)
    {
        out << e05.m_name << " " << e05.m_age;
        return out;
    }
public:
    E05() {}
    E05(string name, int age) :m_name(name), m_age(age){}
    ~E05(){}
private:
    string& m_name;
    const int m_age;
};
此时编译器不会自动生成默认构造函数,reference对象无法更改指向的对象,const成员也无法更改,基于以上原因,默认赋值构造函数不会生成
此外,如果base class将赋值构造函数声明为private,编译器将拒绝为derived class生成一个赋值构造函数

猜你喜欢

转载自blog.csdn.net/baidu_25539425/article/details/79889607