# c++中的複合與繼承相關建構函式的呼叫先後
阿新 • • 發佈:2018-12-18
複合關係
#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(const B& other):A(other),....,..... {}; //B的拷貝建構函式呼叫父類A的拷貝建構函式
B& operator=(const B& other){
A::operator=(other); //B的賦值建構函式呼叫父類A的賦值建構函式
.......
}