cod*_*ode 7 c++ inheritance virtual-inheritance c++11
为什么打印20000?代码在继承序列中一直显式调用特定的基础构造函数,但忽略指定的构造函数并使用默认构造函数.
#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;
}
Run Code Online (Sandbox Code Playgroud)
Igo*_*nik 10
虚基类必须由派生最多的类构造; 考虑到钻石形状的层次结构的可能性,这是唯一有意义的方法.
在您的情况下,Prius构造Car使用其默认构造函数.如果你想要其他构造函数,你必须明确地调用它,就像在
Prius(double b) : Car(b), Toyota(b) {}
Run Code Online (Sandbox Code Playgroud)