c++ - 虚基类初始化

标签 c++ c++11 constructor virtual-inheritance ctor-initializer

我正在做一个测试,我很难理解这个:

#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) {}
};

Live Run

Toyota 是一辆 Car 并且不需要虚拟继承。

阅读here关于虚拟继承如果你的测试是关于虚拟继承

关于c++ - 虚基类初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52112556/

相关文章:

c++ - 如何确定其他进程是否正在使用文件描述符?

c++ - 将 std::array 转换为 std::vector

c++ - 数组和类聚合类型的统一初始化

java - 了解构造函数(非常简单的代码)

C++ 共享库 undefined reference

java - 将 Java jar 文件转换为 cpp

c++ - cv::内存位置异常发生错误

c++ - C++ 中具有可变参数签名的函数映射

java - 错误 : the constructor intent is undefined

c++ - C++ 构造函数名称后面的冒号有什么作用?