4.20 修改题4.19,通过对象指针访问对象数组,是程序以相反的顺序显示对象数组的qu*price。
#include<iostream>
using namespace std;
class book{
public:
book(int q,int p)
{
qu=q; price=p;
}
void show()
{
cout<<"qu*price="<<qu*price<<endl;
}
private:
int qu;
int price;
};
int main()
{
book *b1;
book b[5]={
book(1,10),
book(2,20),
book(3,30),
book(4,40),
book(5,50),
};
b1=&b[4];
int i;
for(i=0;i<5;i++,b1--)
b1->show();
for(int j=0;i<5;i++)
b[j].show();
system("pause");
return 0;
}
4.21 编写一个程序,已有若干个学生的数据,包括学号、姓名、成绩,要求输出这些学生的数据并计算出学生人数和平均成绩(要求将学生人数和总成绩用静态数据成员表示)。
#include<iostream>
#include<string>
using namespace std;
class student{
public:
student(string name1,float score1);
void show();
void show_count_sum_ave();
private:
int num;
string name;
float score;
static int count;
static float sum;
float ave;
};
student::student(string name1,float score1)
{
name=name1;
score=score1;
++count;
sum+=score;
ave=sum/count;
}
void student::show()
{
cout<<"学号"<<num<<endl;
cout<<"姓名"<<name<<endl;
cout<<"成绩"<<score<<endl;
}
void student::show_count_sum_ave()
{
cout<<"学生人数:"<<count<<endl;
cout<<"总成绩:"<<sum<<endl;
cout<<"平均成绩:"<<ave<<endl;
}
int student::count=0;
float student::sum=0;
int main()
{
student stu1("A",90);
stu1.show();
stu1.show_count_sum_ave();
student stu2("B",80);
stu2.show();
stu2.show_count_sum_ave();
student stu3("C",70);
stu3.show();
stu3.show_count_sum_ave();
system("pause");
return 0;
}