虚基类的实现
//
题目描述
main()函数已经写好,需要完善类的定义。
基类:base,base的子类:base01(实现变量+10),base02(实现变量+20), Derived 继承自:base01,base02。
参考教材:P172 修改代码。
需要借助:虚基类实现。
int main()
{
int ival = 0;
cin >> ival;
Derived obj(ival);
return 0;
}
输入
5
输出
base=5
in base01(), m_a = 15
in base02(), m_a = 35
base01::m_a = 35
base02::m_a = 35
样例输入 Copy
10
样例输出 Copy
Base=10
in Base01(), m_a = 20
in Base02(), m_a = 40
Base01::m_a = 40
Base02::m_a = 40
#include <iostream>
using namespace std;
class Base {
public:
Base(int a) {
m_a = a;
cout << "Base=" << m_a <<endl;
}
int m_a;
};
class Base01 :virtual public Base {
public:
Base01(int a):Base(a) {
m_a = m_a + 10;
cout << "in Base01(), m_a = " << m_a << endl;
}
};
class Base02 :virtual public Base {
public:
Base02(int a) :Base(a) {
m_a = m_a + 20;
cout << "in Base02(), m_a = " << m_a << endl;
}
};
class Derived :public Base01, public Base02 {
public:
Derived(int a) :Base(a), Base01(a), Base02(a) {
cout << "Base01::m_a = " << Base01::m_a << endl;
cout << "Base02::m_a = " << Base02::m_a << endl;
}
};
|