1.类嵌套定义
C++的类中的可以是另一个类的成员
复制代码
1
2
3
4
5class A { } class B { A a; }
注意:
1、当类作为另一个类的成员时,先构造类的成员的类,再构造自身。
2、析构函数,先执行本身,再执行成员对象类。遵循栈的先进后出的原则。
2.示例
复制代码
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#include<iostream> #include<string> using namespace std; class shoe { public: string color; shoe(string x):color{x} { cout << "shoe构造函数调用" << endl; } ~shoe() { cout << "shoe析构函数调用" << endl; } }; class person { public: string n_name; shoe n_shoe; person(string x, string y) :n_name{ x }, n_shoe{ y } {cout << "person构造函数调用" << endl; } ~person() { cout << "person析构函数调用" << endl; } }; int main() { person p{ "xiaoming","red" }; cout << p.n_name << endl; cout << p.n_shoe.color<<endl; }
结果:
shoe构造函数调用
person构造函数调用
xiaoming
red
person析构函数调用
shoe析构函数调用
最后
以上就是孤独水壶最近收集整理的关于C++类嵌套1.类嵌套定义的全部内容,更多相关C++类嵌套1内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复