這可能是一個明顯的答案或重複的問題。如果是這樣,對不起,我會刪除它。爲什麼複製構造函數不像默認構造函數或析構函數那樣「鏈接」?
爲什麼不鏈接複製構造函數(如默認ctors或dtors),以便在調用派生類的複製構造函數之前調用基類的複製構造函數?使用拷貝構造函數和析構函數時,它們分別在從基到衍生和從基到鏈的鏈中調用。爲什麼複製構造函數不是這種情況?例如,下面的代碼:
class Base {
public:
Base() : basedata(rand()) { }
Base(const Base& src) : basedata(src.basedata) {
cout << "Base::Base(const Base&)" << endl;
}
void printdata() {
cout << basedata << endl;
}
private:
int basedata;
};
class Derived : public Base {
public:
Derived() { }
Derived(const Derived& d) {
cout << "Derived::Derived(const Derived&)" << endl;
}
};
srand(time(0));
Derived d1; // basedata is initialised to rand() thanks to Base::Base()
d1.printdata(); // prints the random number
Derived d2 = d1; // basedata is initialised to rand() again from Base::Base()
// Derived::Derived(const Derived&) is called but not
// Base::Base(const Base&)
d2.printdata(); // prints a different random number
拷貝構造函數不會(也不能)真正使對象的副本,因爲Derived::Derived(const Derived&)
無法訪問basedata
去改變它。
是否有一些基本的東西我錯過了複製構造函數,這樣我的心智模型是不正確的,或者是否存在這種設計的一些神祕(或不神祕)原因?
@ybungalobill已經證明它是可能的,而且很容易。我認爲你的問題是「爲什麼他們不會自動鏈接***?「 – 2012-01-07 21:06:31
@AaronMcDaid是的,這是我的問題,但也已經被回答在 – 2012-01-07 21:07:23
@BenVoigt是的,我想知道爲什麼一個明確寫的不像一個明確寫的構造函數,但這個問題已經回答了一段時間。 – 2012-01-29 23:11:37