问题描述:
(2)阅读程序,写出执行结果
#include <iostream> using namespace std; class Base { public: Base(char i) { cout<<"Base constructor. --"<<i<<endl; } }; class Derived1:virtual public Base { public: Derived1(char i,char j):Base(i) { cout<<"Derived1 constructor. --"<<j<<endl; } }; class Derived2:virtual public Base { public: Derived2(char i,char j):Base(i) { cout<<"Derived2 constructor. --"<<j<<endl; } }; class MyDerived:public Derived1,public Derived2 { public: MyDerived(char i,char j,char k,char l,char m,char n,char x): Derived2(i,j), Derived1(k,l), Base(m), d(n) { cout<<"MyDerived constructor. --"<<x<<endl; } private: Base d; }; int main() { MyDerived obj('A','B','C','D','E','F','G'); return 0; }
预计运行结果:
Base constructor.--A
Derived1 constructor--B
Base constructor.--C
Derived2 constructor.--D
Base constructor.--E
Base constructor.--F
MyDerived constructor.--G
实际运行结果:
错误分析:因为是虚继承所以
MyDerived(char i,char j,char k,char l,char m,char n,char x): Derived2(i,j), Derived1(k,l), Base(m), d(n) { cout<<"MyDerived constructor. --"<<x<<endl; }
中先执行 Base(m)所以先输出
Base constructor.--E
然后以为消除2义性Derived1和Derived2中关于Base的构造函数不在调用,所以输出:
Derived1 constructor--D
Derived2 constructor--B
然后执行d(n);输出
Base constructor.--F
最后执行cout<<"MyDerived constructor.--G"<<‘\12‘;输出:
MyDerived constructor.--G
有点绕呢。
时间: 2024-10-27 01:36:46