已知Base类包含一个protected的整型变量x,同时包含一个public的print()函数;其他类没有数据成员。 根据下图将程序补充完整(主要是补充每个类的构造函数)。 程序运行结果: Base()... Base1()... x=1 Base()... Base2()... x=2 Base()... Base1()... Base2()... Derive()... x=3 请注意,main()函数或给定部分必须按如下所示编写: int main() { Base1 b1(1); b1.print(); Base2 b2(2); b2.print(); Derive d(3); d.print(); return 0; }
时间: 2024-02-22 18:59:07 浏览: 82
代码如下:
```cpp
#include <iostream>
using namespace std;
class Base {
protected:
int x;
public:
Base() { cout << "Base()... "; }
void print() { cout << "x=" << x << endl; }
};
class Base1 : virtual public Base {
public:
Base1(int a) { x = a; cout << "Base1()... "; }
};
class Base2 : virtual public Base {
public:
Base2(int a) { x = a; cout << "Base2()... "; }
};
class Derive : public Base1, public Base2 {
public:
Derive(int a) : Base(), Base1(a), Base2(a) { cout << "Derive()... "; }
};
int main() {
Base1 b1(1);
b1.print();
Base2 b2(2);
b2.print();
Derive d(3);
d.print();
return 0;
}
```
输出结果为:
```
Base()... Base1()... x=1
Base()... Base2()... x=2
Base()... Base1()... Base2()... Derive()... x=3
```
阅读全文