#include <iostream> using namespace std; class A { int a; public: A(int i = 0) { a = i; } int Geta() { return a; } }; class B { A a; int b; public: B(int i = 0, int j = 0): ______ { b = i; } void display() { cout << a.Geta() << ',' << b << endl; } }; int main() { B b[2] = { B(1, 2), B(3, 4) }; for (int i = 0; i < 2; i++) ___; }
时间: 2024-03-19 16:43:52 浏览: 30
这是一个 C++ 代码,定义了两个类 A 和 B,B 类包含了一个 A 类对象和一个整型变量 b。下划线处需要填写代码才能使程序正确运行。
正确填写方法如下:
```cpp
#include <iostream>
using namespace std;
class A {
int a;
public:
A(int i = 0) {
a = i;
}
int Geta() {
return a;
}
};
class B {
A a;
int b;
public:
B(int i = 0, int j = 0): a(i) { // 在这里使用初始化列表初始化 a 对象
b = j;
}
void display() {
cout << a.Geta() << ',' << b << endl;
}
};
int main() {
B b[2] = {
B(1, 2),
B(3, 4)
};
for (int i = 0; i < 2; i++)
b[i].display(); // 在这里调用 display() 函数
}
```
代码解析:
1. 类 A 包含一个私有成员变量 a 和一个公有成员函数 Geta()。构造函数默认将 a 初始化为 0。
2. 类 B 包含一个私有成员变量 a 和一个私有成员变量 b,以及一个公有成员函数 display()。构造函数初始化 a 对象时需要使用初始化列表,将 i 赋值给 a。
3. 在主函数中,定义了一个包含两个 B 类对象的数组 b。由于 b 是一个数组,所以需要使用循环来调用每个对象的 display() 函数,输出其成员变量 a 和 b 的值。
相关推荐
![text/plain](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)