3.下列程序的运行结果如下,请完善程序。 (注:提交答案时要写清楚每空对应的编号,如:(1)*** (2)*** (3)***) Cons A:4 Cons B:2 Cons M:6 Cons C:8 #include <iostream> using namespace std; class A { int j; public: A( int i ) { j=i; cout << "Cons A:" << i << endl; } }; class B: public A { int k; public: B( int x, int y ): (1) { k=x; cout << "Cons B:" << k << endl; } }; class M { public: M( int n ){cout << "Cons M:" << n << endl; } }; class C: public B { int p; M member; public: C(int a, int b, int c, int d):B ( a , b ), (2) { p=d; cout << "Cons C:" << p <<endl; } }; void main( ) { C obj ( 2, 4, 6, 8 ); }
时间: 2024-03-10 18:46:47 浏览: 16
下列程序的完整版本如下:
```cpp
#include <iostream>
using namespace std;
class A {
int j;
public:
A(int i) {
j = i;
cout << "Cons A:" << i << endl;
}
};
class B : public A {
int k;
public:
B(int x, int y) : A(y) { // (1) 调用A类的构造函数,初始化A类的成员变量
k = x;
cout << "Cons B:" << k << endl;
}
};
class M {
public:
M(int n) {
cout << "Cons M:" << n << endl;
}
};
class C : public B {
int p;
M member;
public:
C(int a, int b, int c, int d) : B(a, c), member(d) { // (2) 调用B类的构造函数,初始化B类的成员变量,调用M类的构造函数,初始化M类的成员变量
p = d;
cout << "Cons C:" << p << endl;
}
};
int main() {
C obj(2, 4, 6, 8);
return 0;
}
```
程序的输出结果为:
```
Cons A:4
Cons B:2
Cons M:6
Cons C:8
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)