设计Person类,成员数据包含姓名(char name[40])年龄(int age)。 程序的功能:首先读入n个人的姓名和年龄,然后统计所有人的年龄总和;最后计算所有人的平均年龄并输出。 main函数已给定,提交时只需要提交main函数外的代码部分。 #include<iostream> #include<cstring> using namespace std; //你提交的代码在这里 int main() { int n,i; cin>>n; Person *person=new Person[n+1]; for(i=1;i<=n;i++) cin>>person[i]; for(i=0;i<=n;i++) cout<<person[i]<<endl; for(i=1;i<=n;i++) person[0]=person[0]+person[i]; cout<<"average age:"<<person[0].GetAge()/(double)n<<endl; delete[] person; return 0; }输入5 Alice 24 Tom 32 White 26 Jack 27 Allen 18输出name=NULL,age=0 name=Alice,age=24 name=Tom,age=32 name=White,age=26 name=Jack,age=27 name=Allen,age=18 average age:25.4请补充完整代码
时间: 2024-03-26 13:36:19 浏览: 83
java代码-使用java构造Person类。包括姓名(name),性别和年龄(age)的源代码
5星 · 资源好评率100%
```
#include<iostream>
#include<cstring>
using namespace std;
class Person {
private:
char name[40];
int age;
public:
Person() {
strcpy(name, "NULL");
age = 0;
}
friend istream& operator>>(istream& in, Person& p);
friend ostream& operator<<(ostream& out, const Person& p);
Person operator+(const Person& p) const {
Person res;
res.age = age + p.age;
return res;
}
int GetAge() const {
return age;
}
};
istream& operator>>(istream& in, Person& p) {
in >> p.name >> p.age;
return in;
}
ostream& operator<<(ostream& out, const Person& p) {
out << "name=" << p.name << ",age=" << p.age;
return out;
}
int main() {
int n, i;
cin >> n;
Person* person = new Person[n + 1];
for (i = 1; i <= n; i++)
cin >> person[i];
for (i = 0; i <= n; i++)
cout << person[i] << endl;
for (i = 1; i <= n; i++)
person[0] = person[0] + person[i];
cout << "average age:" << person[0].GetAge() / (double)n << endl;
delete[] person;
return 0;
}
```
阅读全文