c++實驗二(2)


建立一個名為CStudent的類,該類有以下幾個屬性:學號、姓名(使用字符指針)、成績,並為上述屬性定義相應的方法。
用C++ 面向對象的程序設計方法,找到並輸出存放在CStudent類動態數組中學生成績最高的學生信息(需考慮分數相同的情況,輸出學號、姓名和成績)。


#include<iostream>
#include<cstring>
using namespace std;
class Cstudent
{
private :
long long number;
char *p;//字符指針
int score;
public:
Cstudent(long n,char *q,int s);//默認構造
Cstudent(const Cstudent &s);//復制構造
friend void max(Cstudent*st,int count1);//友元函數方便后面比較成績大小 實質上就是一個數組排序;
void input();//輸入相應的數據
void show();//展示
~Cstudent(); //析構函數
};
Cstudent::Cstudent(long n=0,char *q="no mame",int s=0)//有默認值
{
p=new char[20];//只用在構造函數的地方分配空間
strcpy(p,q);
number=n;
score=s;
}
Cstudent::Cstudent(const Cstudent &s)
{
number=s.number;
score=s.score;
p=new char (*s.p);//深復制函數
}
void Cstudent:: input()//錄入數據
{
long long num;
int s;
cout<<"請輸入姓名:"<<endl;
gets(p);
cout<<"請輸入學號,成績:"<<endl;
cin>>num>>s;
number=num;
score=s;
cin.ignore();
}
void Cstudent ::show()
{
cout<<"姓名:";
puts(p);
cout<<"學號:"<<number<<endl<<"成績:"<<score<<endl;
}
Cstudent::~Cstudent()
{
delete []p;//與前面的new對應
}
void max(Cstudent*st,int count1)
{
int maxx=0;
int c=0;
int j;
for(int i=0;i<count1;i++)
{
if(st[i].score>maxx)
{
maxx=st[i].score;
j=i;
}
}
for(int i=0;i<count1;i++)
{
if(st[i].score==maxx) c++;
}
if(c==1)
{
cout<<"分數最高的同學是:"<<endl;
st[j].show();
}
else
{
cout<<"下面的同學並列最高分:"<<endl;
for(int i=0;i<count1;i++)
{
if(st[i].score==maxx)
{
st[i].show();
cout<<endl;
}
}
}
}
int main()
{ cout<<"請輸入對象的個數:"<<endl;
int a;
cin>>a;
cin.ignore();
const int count=a;
Cstudent*str=new Cstudent[count];
for(int i=0;i<count;i++)
{
str[i].input();
}
max(str,count);
return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM