class Copy {
public:
Copy(){}
Copy(int c) : c_(c){}
private:
int c_;
};
class Copytest : public Copy {
public:
Copytest(){}
Copytest(int a, int c) : a_(a), Copy(c) {
}
Copytest(const Copytest& c) : Copy(c) {
a_ = c.a_;
}
Copytest& operator=(const Copytest& c) {
// 把自身指派給自身的情況, 其實這裡也可以不用
if (this == &c)
return *this;
Copy::operator=(c);
a_ = c.a_;
return *this;
}
#if 0
//預設生成
Copytest();
Copytest(const CopyTest& c);
Copytest& operator=(const Copytest& c);
// 析構函數
~Copytest();
// 在c++11之後:移動構造函數和移動指派運算符
CopyTest(Copytest&& c);
CopyTest& operator=(Copytest&& c);
#endif
private:
int a_{10};
};
是以在派生類中(基類有非靜态資料成員),派生類構造函數需要調用基類構造函數、派生類拷貝構造函數需要調用基類拷貝構造函數、派生類指派運算符需要調用基類指派運算符。