写出包含对象数组的c++程序
时间: 2023-10-04 20:08:51 浏览: 31
以下是一个简单的 C++ 程序,其中包含对象数组的示例:
```cpp
#include <iostream>
#include <string>
using namespace std;
class Person {
private:
string name;
int age;
public:
void setInfo(string n, int a) {
name = n;
age = a;
}
void printInfo() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
int main() {
const int SIZE = 3;
Person people[SIZE];
string name;
int age;
for (int i = 0; i < SIZE; i++) {
cout << "Enter name of person " << i+1 << ": ";
cin >> name;
cout << "Enter age of person " << i+1 << ": ";
cin >> age;
people[i].setInfo(name, age);
}
cout << endl << "People's information:" << endl;
for (int i = 0; i < SIZE; i++) {
people[i].printInfo();
}
return 0;
}
```
在此示例中,我们定义了一个 Person 类,该类包含名称和年龄属性,并具有 setInfo() 和 printInfo() 方法。然后,在主函数中,我们创建了一个名为 people 的 Person 类型数组,其大小为 SIZE。然后,我们使用 for 循环遍历该数组,并使用 setInfo() 方法为每个人设置名称和年龄。最后,我们再使用 for 循环遍历该数组,并使用 printInfo() 方法打印每个人的信息。