2

I am working on a test and I have hard time to understand this one:

#include <iostream>

struct Car
{
 Car() : price(20000) {}
 Car(double b) : price(b*1.1) {}
 double price;
};
struct Toyota : public virtual Car 
{
 Toyota(double b) : Car(b) {}
};

struct Prius : public Toyota
{
 Prius(double b) : Toyota(b)  {}
};

int main(int argc, char** argv)
{
 Prius p(30000);

 std::cout << p.price << std::endl;

 return 0;
}

The returned value is 20 000, but actually I do not not understand the why:

All sub-objects representing virtual base classes are initialized by the constructor of the most derived class. If the constructor of the most derived class does not specify a mem-initializer for a virtual base class V, then V's default construtor is called to initialize the virtual base class subobject.

And I tried different way to create a constructor in the derived class but I got errors from the compiler.

Does anyone provide an explanation and how to create such constructor?

4

2 回答 2

0

删除虚拟继承:

struct Car
{
 Car() : price(20000) {}
 Car(double b) : price(b*1.1) {}
 double price;
 virtual ~Car() = default;
};

struct Toyota : public Car 
{
 Toyota(double b) : Car(b) {}
};

现场运行

Toyotais-aCar并且不需要虚拟继承。

如果您的测试是关于虚拟继承的,请在此处阅读有关虚拟继承的信息

于 2018-08-31T09:47:42.700 回答
0

只需为(间接)虚拟基础添加 mem-initializer:

Prius(double b) : Car(b), Toyota(b)  {}

在 coliru 上看到它。

虚拟继承确保虚拟基在完整对象中只存在一次。为此,初始化虚拟基地不可能是某个中间基地的任务,甚至可能不是唯一一个要求它的中间基地:哪个应该获得批准?
相反,ctor被分成两部分:一个用于初始化除虚拟基之外的所有内容,无论是直接还是间接,并且由派生类使用,一个首先初始化虚拟基,然后将其余部分委托给前者,即一个要求创建一个完整的对象。

如果您弄错了 mem-initializers 的顺序,大多数编译器都会发出警告,因此您稍后不会对您的代码实际执行的操作感到惊讶。那可能是您的编译器指出的错误...

于 2018-08-31T09:44:10.703 回答