类类型是我们自己定义的新类型,这个类型在C++中并不存在。
C++允许(希望)我们根据自己的需要,定义自己想要的类型来完成我们的工作。
比如,我们可以定义一个学生类:
- struct Student
- {
- };
说明:上面的代码定义了一个学生类,注意最后有一个分号作为定义的结束。
类类型的变量又叫对象。
Student student;
上面的代码创建了一个学生对象student。
我们可以给学生类添加成员变量用来存储学生的信息。像下面这样:
- struct Student
- {
- long long id;//学号
- int age;//年龄
- };
成员变量也是变量,可以通过对象成员操作符(对象后面跟着一个句点号,见下面的代码)来获得你想要的成员变量。
上面的成员变量 id 的类型是long long。
是一个范围很大的整数类型,用来表示学生学号绰绰有余。
- Student student;
- //使用点号(对象成员操作符)来访问类对象的成员变量
- student.id = 2022092345;//张三的学号2022届9月份入学,个人编号2345;
- student.age = 20;//张三的年龄20岁
- #include
- #include
- using namespace std;
-
- struct Student
- {
- long long id;//学号
- string name;// 姓名
- int age;//年龄
- };
-
- int main(void)
- {
- Student student;
- student.id = 2022092345;
- student.name = "Newton";
- student.age = 20;
-
- cout << "id = " << student.id << endl;
- cout << "name = " << student.name << endl;
- cout << "age = " << student.age<< endl;
-
-
- return 0;//main end
- }
