我不明白爲什麼在下面的代碼中,當我instanciate類型爲daughter
的對象時,默認的grandmother()
構造函數被調用?爲什麼在虛擬繼承中調用Default構造函數?
我認爲應該調用grandmother(int)
構造函數(遵循我的mother
類構造函數的規範),或者由於虛擬繼承,此代碼根本不應編譯。
這裏編譯器在我的後面默默地調用grandmother
默認構造函數,而我從來沒有要求它。
#include <iostream>
class grandmother {
public:
grandmother() {
std::cout << "grandmother (default)" << std::endl;
}
grandmother(int attr) {
std::cout << "grandmother: " << attr << std::endl;
}
};
class mother: virtual public grandmother {
public:
mother(int attr) : grandmother(attr) {
std::cout << "mother: " << attr << std::endl;
}
};
class daughter: virtual public mother {
public:
daughter(int attr) : mother(attr) {
std::cout << "daughter: " << attr << std::endl;
}
};
int main() {
daughter x(0);
}
什麼編譯器(和版本)?你用什麼論據來編譯它? – orlp 2012-03-28 12:46:43
gcc 4.6.3 20120306(Red Hat 4.6.3-2)on fedora 15.參數是:-O0 -g3 -Wall -c -fmessage-length = 0 – 2012-03-28 12:47:29
g ++ 4.1.2有同樣的問題:http:// codepad.org/L0jBXfSP – orlp 2012-03-28 12:49:57