在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;
}
此代码也可以正常运行