第四章

4.声明一个student类,在该类中包括一个数据成员score、两个静态数据成员sum和count

#include<iostream>
#include<string>
using namespace std;
class student{
public:
    student(float s);
	static float sum(student &stu);
    static float average(student &stu);
private:
	float score;
	static float total_score;
	static int count;
	float ave;

};
int student::count=0;
float student::total_score=0.0;
student::student(float s=0)
{
	score=s;
	++count;
	total_score=total_score+score;
	ave=total_score/count;
}
float student::sum(student &stu)
{
	cout<<"班级同学的总分为:"<<stu.total_score<<endl;
	return 0;
}
float student::average(student &stu)
{
	cout<<"班级成绩平均分:"<<stu.ave<<endl;
return 0;
}

int main()
{   
	int i;
	cout<<"请输入成绩:"<<endl;
    cin>>i;
	student stu1(i);
	cout<<"请输入下一位同学的成绩"<<endl;
	cin>>i;
    student stu2(i);
	cout<<"请输入下一位同学的成绩"<<endl;
	cin>>i;
    student stu3(i);
	cout<<"请输入下一位同学的成绩"<<endl;
	cin>>i;
   student stu4(i);
	student::sum(stu4);
	student::average(stu4);
	return 0;
}

4.17建立一个对象数组,内放6个学生的数据(学号、成绩),用指针指向数组首元素,输出第2、4、6个学生的数据

#include<iostream>
#include<string>
using namespace std;
class student{
public:
	student (string m ,long n=0,float s=0.0);
	void show();
private:
	long num;
	float score;
	string name;
};
student::student(string m,long n,float s)
{
    name=m;
	num=n;
	score=s;
}
void student::show()
{
	cout<<"该学生的学号为:"<<num<<"    "<<"该学生的名字为:"<<name<<"   "<<"成绩:"<<score<<endl;
}
int main()
{
	student stu[6]={
	    	student("liyi",2222,33),
			student("lihu",4444,55),
			student("huhu",6666,77),
			student("fgfg",5555,66),
			student("grgr",8888,88),
			student("hehe",9999,99)
	};
    student *p;
	p=stu;
	for(int i=0;i<6;i++,p++)
	{
		if(i%2==0)
			continue;
		else
		p->show();
	}
	cout<<endl;
	return 0;
}
		

4.19构建一个类book,其中含有两个私有数据成员qu和price,建立一个有5个元素的数据对象,将qu初始化为1~5,初始化为qu的十倍,显示每个对象的qu和price的值

#include<iostream>
using namespace std;
class Book{
public:
    Book(int q=1,int p=1)
	{
		qu=q;
	    price=p;
	}
	int  showbook();
	Book(){};
	
private:
	int qu,price;
};
int Book::showbook()
{
	
	return (qu*price);
}
int main()
{
	Book b[5]={
		Book(1,10),
		Book(2,20),
		Book(3,30),
		Book(4,40),
		Book(5,50)
	};
        cout<<"b[0]="<<b[0].showbook()<<endl;
		cout<<"b[1]="<<b[1].showbook()<<endl;
		cout<<"b[2]="<<b[2].showbook()<<endl;
		cout<<"b[3]="<<b[3].showbook()<<endl;
		cout<<"b[4]="<<b[4].showbook()<<endl;
		

	return 0;

}

4.20

#include<iostream>
using namespace std;
class book{
public:
	book(int i,int j)
	{
		qu=i;
		price=j;
	}

    void show()
	 {
		cout<<qu*price<<endl;
	 }
private:
	int qu;
	int price;
};
int main()
{
	book bs[5]={
		book(1,10),
		book(2,20),
		book (3,30),
		book(4,40),
		book(5,50)
	};
	book * p;
	p=&bs[4];
	for( ;p>=bs;p--)
	{
		p->show();
	}
	return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值