C ++第12章:C ++类和对象
前开发者教程
2020年1月27日
以下是本章涵盖的主题
- C ++中的类
- 声明对象
- 点运算符
- 箭头运算符
1. C ++中的类
C ++中的类类似于C中的结构。它们用于打包数据成员和成员函数。在类内部定义的变量称为数据成员。编写在类内部的函数称为成员函数。
“类”是用于定义类的关键字。
类的示例:
Class Student { public: int roll_no; void display() { cout<<”In display function”<<endl; } };
注意:
- 默认情况下,数据成员和成员函数都是私有的。
- 课堂结束时应该有一个分号。
- 访问说明符应以冒号“:”结尾。
2.声明对象
创建类后,我们需要创建一个对象。类用于指定对象的结构。对象是类的变量/实例。
声明一个对象:
<class_name> <object_name>;
例:
Student s1;
3.点运算符
声明对象后,该对象可以访问该类的数据成员和成员函数。一个对象只能直接访问“公共”成员。访问私有或受保护的成员将导致错误。
如果创建一个简单的对象,则使用点“。”操作员。
例:
#include<iostream> using namespace std; class Student { public: int roll_no; void display() { cout<<"The roll number of student is = " <<roll_no <<endl; } }; int main() { Student s1; s1.roll_no = 10; s1.display(); }
输出:
The roll number of student is = 10
4.箭头运算符
在上一节中,我们创建了一个简单的对象。我们还可以创建类类型的指针并访问公共成员。如果我们创建一个指针并需要访问成员,则必须使用“->” operator.
例:
#include<iostream> using namespace std; class Student { public: int roll_no; void display() { cout<<"The roll number of student is = " <<roll_no <<endl; } }; int main() { Student s1; Student *s2 = &s1; s2 -> roll_no = 10; s2 -> display(); }
输出:
The roll number of student is = 10
该网站上可用的教程列表:
C编程20+章 | C ++编程80+章 |
100多个编码问题 | 数据结构和算法85+章 |
系统设计20+章 | Shell脚本编写12章 |
4g LTE 60+章节 | 最常见的编码问题 |
5G NR 50+章 | Linux系统编程20+章 |