Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/143.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么在虚拟继承中调用默认构造函数?_C++_Inheritance_Virtual Inheritance - Fatal编程技术网

C++ 为什么在虚拟继承中调用默认构造函数?

C++ 为什么在虚拟继承中调用默认构造函数?,c++,inheritance,virtual-inheritance,C++,Inheritance,Virtual Inheritance,我不明白为什么在下面的代码中,当我实例化类型为子对象的对象时,会调用默认的祖母()构造函数 我认为要么调用granger(int)构造函数(遵循我的mother类构造函数的规范),要么由于虚拟继承,该代码根本不应该编译 在这里,编译器在我的背后默默地调用祖母默认构造函数,而我从未要求过它 #include <iostream> class grandmother { public: grandmother() { std::cout << "gr

我不明白为什么在下面的代码中,当我实例化类型为
子对象
的对象时,会调用默认的
祖母()
构造函数

我认为要么调用
granger(int)
构造函数(遵循我的
mother
类构造函数的规范),要么由于虚拟继承,该代码根本不应该编译

在这里,编译器在我的背后默默地调用
祖母
默认构造函数,而我从未要求过它

#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);
}
#包括
班祖母{
公众:
祖母(){

std::cout当使用虚拟继承时,虚拟基类的构造函数直接由派生最多的类的构造函数调用。在这种情况下,
子类
构造函数直接调用
祖母
构造函数

由于您没有在初始化列表中显式调用
granger
构造函数,因此将调用默认构造函数。若要调用正确的构造函数,请将其更改为:

daugther(int attr) : grandmother(attr), mother(attr) { ... }

另请参见。

什么编译器(和版本)?使用什么参数编译?gcc 4.6.3 20120306(Red Hat 4.6.3-2)在FEDORA 15中。参数是:-O0-G3-WALL-C-FEMANTRONSE=0G++4.1.2有相同的问题:Ubuntu 4.7的带有墙式迂回错误的快照复制了这一点。这完全有意义,谢谢!在层次结构中的所有构造函数都是从最后一个类调用的,而不是由各自的子类调用的。从来没有想到过。C++规范可能是棘手的SOM。有时…谢谢!所以在虚拟继承的情况下,最好是手动调用链的所有构造函数。@Xriuk它指的是使用虚拟继承继承继承的类的构造函数。这是否意味着祖母将被调用两次?在母亲内部调用祖母会发生什么情况?@Youda008它将被称为o除非直接实例化
mother
而不是派生类,否则将忽略来自
mother
的调用。