赞
踩
C++ 中保留了C语言的 struct 关键字,并且加以扩充。在C语言中,struct 只能包含成员变量,不能包含成员函数。而在C++中,struct 类似于 class,既可以包含成员变量,又可以包含成员函数。
C++中的 struct 和 class 基本是通用的,唯有几个细节不同:
使用 class 时,类中的成员默认都是 private 属性的;而使用 struct 时,结构体中的成员默认都是 public 属性的。
class 继承默认是 private 继承,而 struct 继承默认是 public 继承(《C++继承与派生》一章会讲解继承)。
class 可以使用模板,而 struct 不能(《模板、字符串和异常》一章会讲解模板)。
C++ 没有抛弃C语言中的 struct 关键字,其意义就在于给C语言程序开发人员有一个归属感,并且能让C++编译器兼容以前用C语言开发出来的项目。
小例子:
- #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 结构体名 变量名
* struct 结构体名 变量名 = { 成员1值 , 成员2值...}
* 定义结构体时顺便创建变量
小例子:
- //结构体定义
- struct student
- {
- //成员列表
- string name; //姓名
- int age; //年龄
- int score; //分数
- }stu3; //结构体变量创建方式3 int main() {
-
- //结构体变量创建方式1
- struct student stu1; //struct 关键字可以省略
-
- stu1.name = "张三";
- stu1.age = 18;
- stu1.score = 100; cout << "姓名:" << stu1.name << " 年龄:" << stu1.age << " 分数:" << stu1.score << endl;
-
- //结构体变量创建方式2
- struct student stu2 = { "李四",19,60 };
-
- cout << "姓名:" << stu2.name << " 年龄:" << stu2.age << " 分数:" << stu2.score << endl; stu3.name = "王五";
- stu3.age = 18;
- stu3.score = 80; cout << "姓名:" << stu3.name << " 年龄:" << stu3.age << " 分数:" << stu3.score << endl;
-
- system("pause");
-
- return 0;
- }

1、定义结构体时的关键字是struct,不可省略
2、创建结构体变量时,关键字struct可以省略
3、结构体变量利用操作符 ''.'' 访问成员
将自定义的结构体放入到数组中方便维护
struct 结构体名 数组名[元素个数] = { {} , {} , ... {} }
- //结构体定义
- struct student
- {
- //成员列表
- string name; //姓名
- int age; //年龄
- int score; //分数
- }
-
- int main() { //结构体数组
- struct student arr[3]=
- {
- {"张三",18,80 },
- {"李四",19,60 },
- {"王五",20,70 }
- };
-
- for (int i = 0; i < 3; i++)
- {
- cout << "姓名:" << arr[i].name << " 年龄:" << arr[i].age << " 分数:" << arr[i].score << endl;
- }
-
- system("pause");
-
- return 0;
- }

结构体指针:通过指针访问结构体中的成员 * 利用操作符 `-> `可以通过结构体指针访问结构体属性
- //结构体定义
- struct student
- {
- //成员列表
- string name; //姓名
- int age; //年龄
- int score; //分数
- };
-
-
- int main() { struct student stu = { "张三",18,100, }; struct student * p = &stu; p->score = 80; //指针通过 -> 操作符可以访问成员
-
- cout << "姓名:" << p->name << " 年龄:" << p->age << " 分数:" << p->score << endl; system("pause");
-
- return 0;
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。