在例3.29的基础上改写程序,满足条件: (1) Please input the number of students:2 //只有2为输入 1001 18 90 //输入 1002 19 92 //输入 The average score of 2 student is 91 请思考 Student *p=new Student[n]; 的含义,即这种指针的使用。 请注意,main()函数或给定部分必须按如下所示编写: int main() { int n; cout<<"Please input the number of students:"; cin>>n; Student *p=new Student[n]; for(int i=0; i<n; i++) { int num,age; float score; cin>>num>>age>>score; p[i]=Student(num,age,score); p[i].total(); } cout<<"The average score of "<<n<<" student is "<<Student::average()<<endl; if(p!=NULL) delete []p; return 0; }
时间: 2023-12-10 21:41:34 浏览: 63
改写后的程序如下所示:
```
#include <iostream>
using namespace std;
class Student {
private:
int num; //学号
int age; //年龄
float score; //成绩
static float sum; //总成绩
static int count; //学生数量
public:
Student(int n, int a, float s):num(n),age(a),score(s) {}
void total() { sum += score; count++; }
static float average() { return sum / count; }
};
float Student::sum = 0;
int Student::count = 0;
int main() {
int n;
cout << "Please input the number of students:";
cin >> n;
Student *p = new Student[n];
for (int i = 0; i < n; i++) {
int num, age;
float score;
cin >> num >> age >> score;
p[i] = Student(num, age, score);
p[i].total();
}
cout << "The average score of " << n << " student is " << Student::average() << endl;
if (p != NULL) delete[] p;
return 0;
}
```
在原有程序的基础上,我们将输入学生数量的部分改为了固定值2,并且在Student类中添加了静态变量sum和count,用于累加总成绩和学生数量。在main函数中,先使用new运算符动态分配大小为n的Student对象数组,再根据输入的学生信息创建Student对象并调用total函数累加总成绩和学生数量。最后输出平均分并释放动态分配的内存。
Student *p=new Student[n]的含义是在堆上动态分配大小为n个Student对象的连续内存空间,并将其首地址赋给指针变量p。这种指针的使用可以避免在编译时确定数组大小,从而灵活地处理不确定数量的对象。在程序结束时,需要使用delete[] p释放分配的内存,避免内存泄漏。
阅读全文