使用虚继承之后无法将孙子类的参数(color)传给爷爷类了,仅能使用默认构造函数的初始化值,如何解决?
virtual减少了调用次数,但也让值不能传递,如何解决
virtual减少了调用次数,但也让值不能传递,如何解决
2019-10-02
//如果不用默认值,需要从子类的构造函数的初始化列表中传给父类相应的参数,如下: #include <iostream> #include <string> using namespace std; class Persion { public: Persion(string color /*= "red"*/):m_strColor(color){} void play(){cout<<m_strColor<<endl;} protected: string m_strColor; }; class Worker:virtual public Persion { public: Worker(int salary, string color = "yellow"):Persion(color),m_iSalary(salary){} protected: int m_iSalary; }; class Children:virtual public Persion { public: Children(int age,string color = "green"):Persion(color),m_iAge(age){} protected: int m_iAge; }; class ChildLabourer:public Worker,public Children { public: ChildLabourer(int age, int salary, string color): Worker(salary,color),Children(age,color),Persion(color) { } }; int main() { ChildLabourer cl(10,1000,"black"); cl.play(); cl.Worker::play(); cl.Children::play(); cl.Worker::Persion::play(); cl.Children::Persion::play(); cl.Persion::play(); }
举报