创建一个类

c++是一门面向对象的编程语言,而面向对象的基础就是类

使用C++创建一个Student类

class Student//学生类
{
private://私有

	//数据成员
	char Name[10];//姓名
	int Age;//年龄
	int No;//学号

public://公有

	//成员函数
	//输入学生的信息
	void InputStudent(char *name, int age, int no)
	{
		strcpy(Name, name);
		Age = age;
		No = no;
	}

	//输出学生的信息
	void OutputStudent(void)
	{
		cout<<Name<<" "<<Age<<" "<<No<<endl;
	}
};

为了减少类中的代码量可以将成员函数在类中声明,在类外面定义

class Student//学生类
{

public:
	
	//成员函数
	void Input(char *name, int age, int no);
	void Output(void);

private:

	//数据成员
	char Name[20];
	int Age;
	int No;
};

void Student::Input(char *name, int age, int no)
{
	strcpy(Name,name);
	Age = age;
	No = no;
}

void Student::Output(void)
{
	cout<<Name<<" "<<Age<<" "<<No<<endl;
}


测试程序

程序的全部代码:方法1

#include <iostream>
#include <cstring>
#include <cstdlib>

using namespace std;

class Student//学生类
{
private://私有

	//数据成员
	char Name[10];//姓名
	int Age;//年龄
	int No;//学号

public://公有

	//成员函数
	//输入学生的信息
	void InputStudent(char *name, int age, int no)
	{
		strcpy(Name, name);
		Age = age;
		No = no;
	}

	//输出学生的信息
	void OutputStudent(void)
	{
		cout<<Name<<" "<<Age<<" "<<No<<endl;
	}
};

int main()
{
	//定义两个学生结构
	Student stu1, stu2;

	//对学生结构赋值
	stu1.InputStudent("小明", 10, 1);
	stu2.InputStudent("小华", 10, 2);

	//输出学生信息
	stu1.OutputStudent();
	stu2.OutputStudent();

	system("pause");
}


程序代码:将成员函数在类外面定义

#include <iostream>
#include <cstring>
#include <cstdlib>

using namespace std;

class Student//学生类
{

public:
	
	//成员函数
	void Input(char *name, int age, int no);
	void Output(void);

private:

	//数据成员
	char Name[20];
	int Age;
	int No;
};

void Student::Input(char *name, int age, int no)
{
	strcpy(Name,name);
	Age = age;
	No = no;
}

void Student::Output(void)
{
	cout<<Name<<" "<<Age<<" "<<No<<endl;
}

void main()
{
	Student stu1, stu2;

	stu1.Input("小明", 10, 1);
	stu2.Input("小华", 10, 2);

	stu1.Output();
	stu2.Output();

	system("pause");
}

执行结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值