第四章 类和对象的进一步讨论-续



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; 
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值