我正在做一个测试,我很难理解这个:
#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;
}
返回值是20000,其实我也不明白这是为什么:
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.
我尝试了不同的方法在派生类中创建构造函数,但编译器出错了。
有没有人提供解释以及如何创建这样的构造函数?
最佳答案
移除虚拟继承:
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) {}
};
Toyota
是一辆 Car
并且不需要虚拟继承。
阅读here关于虚拟继承如果你的测试是关于虚拟继承
关于c++ - 虚基类初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52112556/