栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++类的实现

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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
#include
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<getStudentID()<getName()<getSex()<getAge()<totalScore()< 

注意:类的数据成员尽量设置成private,用public函数对私有数据成员进行访问,这样的函数称 为接口函数,是本对象和外部进行信息交换的通道。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/348076.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号