c++中的复合与继承相关构造函数的调用先后

复合关系c++中的复合与继承相关构造函数的调用先后

#include <iostream>
class A{
public:
    A(int m=0):a(m){
            std::cout<<"base's defualt构造函数"<<std::endl;
    };
    A(const A& other){
        a=other.a;
        std::cout<<"base's 拷贝构造函数"<<std::endl;
    };
    A& operator=(const A& other){
        std::cout<<"base's 赋值构造函数";
        if(&other==this)
            return *this;

        a=other.a;
        return *this;
    }
private:
    int a;
};

class B{
public:
    B(){}; //调用A的default构造函数
    B(const B& other){}; 
    B& operator=(const B& other){
        return *this;
    }

private:
    A a;
};

默认B 的defualt、拷贝、赋值构造函数都是调用A的defualt构造函数

class B{
public:
    B():a(){}; //调用A的default构造函数
    B(const B& other):a(other.a){}; //调用A的拷贝构造函数
    B& operator=(const B& other){
        a=other.a;                //调用A的赋值构造函数
        return *this;
    }

private:
    A a;
};

经过上面的修改 B的defualt构造函数调用A的defualt构造函数,拷贝构造函数调用A的拷贝构造函数,赋值构造函数调用A的赋值构造函数。

关于继承的关系 A为B 的父类 在B的任何构造函数进行对继承下来A的部分进行构造,编译器会默认调用A的defualt构造进行构造。
但是如果这样并不能实现真正的拷贝对于A类中成员,因为 A的defualt的构造函数只是起到了初始化作用。
如果想要B的拷贝构造函数调用父类A的拷贝构造函数
B的赋值构造函数调用A的赋值构造函数
所以可以如下设计:

B(const B& other):A(other),....,..... {}; //B的拷贝构造函数调用父类A的拷贝构造函数

B& operator=(const B& other){
A::operator=(other);  //B的赋值构造函数调用父类A的赋值构造函数 
.......
}