C++类的实现


声明学生类 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函数对私有数据成员进行访问,这样的函数称 为接口函数,是本对象和外部进行信息交换的通道。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值