C++ 中保留了C语言的 struct 关键字,并且加以扩充。在C语言中,struct 只能包含成员变量,不能包含成员函数。而在C++中,struct 类似于 class,既可以包含成员变量,又可以包含成员函数。
C++中的 struct 和 class 基本是通用的,唯有几个细节不同:
C++ 没有抛弃C语言中的 struct 关键字,其意义就在于给C语言程序开发人员有一个归属感,并且能让C++编译器兼容以前用C语言开发出来的项目。
在编写C++代码时,我强烈建议使用 class 来定义类,而使用 struct 来定义结构体,这样做语义更加明确。
使用 struct 来定义类的一个反面教材:
- #include <iostream>
- using namespace std;
- struct Student{
- Student(char *name, int age, float score);
- void show();
- char *m_name;
- int m_age;
- float m_score;
- };
- Student::Student(char *name, int age, float score): m_name(name), m_age(age), m_score(score){ }
- void Student::show(){
- cout<<m_name<<"的年龄是"<<m_age<<",成绩是"<<m_score<<endl;
- }
- int main(){
- Student stu("小明", 15, 92.5f);
- stu.show();
- Student *pstu = new Student("李华", 16, 96);
- pstu -> show();
- return 0;
- }
运行结果:
这段代码可以通过编译,说明 struct 默认的成员都是 public 属性的,否则不能通过对象访问成员函数。如果将 struct 关键字替换为 class,那么就会编译报错。