初步认识类

在c语言中,可以使用struct来自定义一种新的类型
问题:c语言中struct中可以放函数吗?—不能,只能放数据
验证:
在c语言中

struct student
{
	char _name[20];
	int  _age;

	void setage(int age)
	{
		_age = age;
	}
};

代码运行失败–》说明:c语言中的结构体内部是不能放函数的
上述代码在C++中
代码编译成功–》说明:c++中的结构体是能放函数的

#include <iostream>
using namespace std;
//在C++中,struct定义出来的类型就可以看成是一个类了
//C语言中的结构体,在c++中变成-->定义了一个类
//只不过在c++中,如果要定义一个类,我们更喜欢使用class的关键字
struct Student
{
	结构体中的变量
	char _name[20];
	char _gender[3];
	int  _age;

	结构体中的函数
	初始化
	void InitStudent(char name[], char gender[], int age)
	{
		strcpy(_name, name);
		strcpy(_gender,gender);
		_age = age; 
	}

	打印
	void PrintStudent()
	{
		cout << _name << " " << _gender << " " << _age << endl;
	}

	void SetAge(int age)
	{
		_age = age;
	}
};
int main()
{
	在c语言中可以这样定义
	struct Student s1;
	s1._age = 10;

	在c++中可以这样定义
	Student s2;
	s2.InitStudent("peter", "男", 18);
	s2.SetAge(10);

	return 0;
}

只不过在c++中,如果要定义一个类,我们更喜欢使用class的关键字
即:

#include <iostream>
using namespace std;
class Student
{
	结构体中的变量
	char _name[20];
	char _gender[3];
	int  _age;

	结构体中的函数
	初始化
	void InitStudent(char name[], char gender[], int age)
	{
		strcpy(_name, name);
		strcpy(_gender,gender);
		_age = age; 
	}

	打印
	void PrintStudent()
	{
		cout << _name << " " << _gender << " " << _age << endl;
	}

	void SetAge(int age)
	{
		_age = age;
	}
};
int main()
{
	return 0;
}

此代码也可以正常运行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值