声明学生类 Student
定义以下 private成员: unsigned int studentID; char*name=new char[20]; char*sex=new char[10]; unsigned int age; float mathScore; float englishScore; float CPPScore;
定义以下public成员:
①构造函数,带参数如下 Student(unsigned int ID, const char *newName, const char *newSex, unsigned int newAge,float newMathScore,float newEnglishScore,float newCPPScore)将各形式参数赋值给相应的私有成员变量,注意字符串用strcpy。 ②析构函数,将name和sex的空间释放 ③unsigned int getSutdentI函数,返回studentID; char*getName0函数,返回 name;char*getSex()函数,返回sex unsigned;?int getAge()函数,返回age;float totalScore()函数,返回 mathScroe,englishScore,CPPScore 三个成绩的和。
在main函数中定义一个Student类对象指针stu,用new创建,根据构造函数的参数列表给出参数。 用cout输出 stu的 studentID, name, sex, age,分别调用公有get接口函数实现。 最后输出总成绩,用totalScore实现。 释放 stu内存。
#include<iostream>
#include<string.h>
using namespace std;
class Student
{
public:
Student(unsigned int ID,const char*newName,const char*newSex,unsigned int newAge,float newMathScore,float newEnglishScore,float newCPPScore)
{
studentID=ID;
strcpy(name,newName);
strcpy(sex,newSex);
age=newAge;
mathScore=newMathScore;
englishScore=newEnglishScore;
CPPScore=newCPPScore;
}
~Student()
{
delete[] name;
delete[] sex;
}
unsigned int getStudentID()
{
return studentID;
}
char *getName()
{
return name;
}
char *getSex()
{
return sex;
}
unsigned int getAge()
{
return age;
}
float totalScore()
{
return mathScore+englishScore+CPPScore;
}
private:
unsigned int studentID;
char *name=new char[20];
char *sex=new char[10];
unsigned int age;
float mathScore;
float englishScore;
float CPPScore;
};
int main()
{
Student *stu=new Student(2019,"lt","Woman",20,98.5,96,100);
cout<<stu->getStudentID()<<endl;
cout<<stu->getName()<<endl;
cout<<stu->getSex()<<endl;
cout<<stu->getAge()<<endl;
cout<<stu->totalScore()<<endl;
delete stu;
return 0;
}
注意:类的数据成员尽量设置成private,用public函数对私有数据成员进行访问,这样的函数称 为接口函数,是本对象和外部进行信息交换的通道。
|