编写类
编写类时,需要指定行为和方法,还需要指定属性和数据成员。
编写类的两个要素:定义类本身和定义类的方法。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20#include <iostream> using namespace std; #include<string> class student//学生类 { public: student() { } private: string name; int age; }; int main() { student one;//类的实例->对象 return 0; }
类的三大特点
- 封装
- 继承
- 多态
类的访问限定符
- public:公有属性 ,类的成员可以从类外直接访问。
- protected:类的成员不可以从类外直接访问。
- private:与protected相同。
- 类的每个访问限定符可以多次在类中使用,作用域为从该限定符开始到下一个限定符之前结束。
- 如果class定义的类没有定义限定符,则默认为私有《private》
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20#include <iostream> using namespace std; #include<string> class student//学生类 { public: student() { } string name; private: int age; }; int main() { student one;//类的实例->对象 one.name = ("小明"); // one.age = 12;不可访问,类中的私有成员变量不可在类外访问。 return 0; }
类的定义
- 类的对象可以直接通过(.)和(->)访问公有成员。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35#include <iostream> using namespace std; #include<string> class student//学生类 { public: void display() { cout << "姓名: " << name << " 年龄: " << age << endl; } public: string name; int age; }; int main() { student one; one.name = ("小明"); one.age = 12; one.display(); student* p = new student; p->name = ("小红"); p->age = 13; p->display(); return 0; } /* 姓名: 小明 年龄: 12 姓名: 小红 年龄: 13 F:新建文件夹myfirstDebugmyfirst.exe (进程 10024)已退出,代码为 0。 要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。 按任意键关闭此窗口. . . */
类外定义成员函数,必须用::(作用域解析符)支出它属于那个类的成员函数。
复制代码
1
2
3
4
5
6
7
8
9
10class person { public: void display();类内声明 } void person::display()//类外定义 { //........ }
类的大小
类中的成员函数是公有的,该类的对象共享这些成员函数。因此每个对象的大小为类内成员变量大小之和。
最后
以上就是忧伤西牛最近收集整理的关于类和对象的基础编写类的全部内容,更多相关类和对象内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复