1 #include <iostream> 2 3 class My1{ 4 public: 5 My1(); 6 ~My1(); 7 }; 8 9 class My2{ 10 public: 11 My2(); 12 ~My2(); 13 My1 mymm; 14 }; 15 16 class My3{ 17 public: 18 My3(); 19 ~My3(); 20 My1 mymm; 21 }; 22 23 My1::My1(){ 24 std::cout<<"my1gouzao"<<std::endl; 25 } 26 My1::~My1(){ 27 std::cout<<"my1xigou"<<std::endl; 28 } 29 My2::My2(){ 30 std::cout<<"my2gouzao"<<std::endl; 31 } 32 My2::~My2(){ 33 std::cout<<"my2xigou"<<std::endl; 34 } 35 My3::My3(){ 36 std::cout<<"my3gouzao"<<std::endl; 37 } 38 My3::~My3(){ 39 std::cout<<"my3xigou"<<std::endl; 40 } 41 42 int main(){ 43 My2 mym2; 44 My3 mym3; 45 }
例1:嵌套类的构造与析构
例2:在一个类中创建另一个类的实例(直接访问)
1 #include <iostream> 2 using namespace std; 3 class My1{ 4 public: 5 My1(); 6 ~My1(); 7 int i; 8 }; 9 10 class My2{ 11 public: 12 My2(); 13 ~My2(); 14 void say(); 15 My1 my1; 16 }; 17 18 My1::My1(){ 19 cout<<"my1gouzao"<<endl; 20 } 21 void My2::say(){ 22 my1.i = 200; 23 cout<<my1.i<<endl; 24 } 25 My1::~My1(){ 26 cout<<"my1xigou"<<endl; 27 } 28 My2::My2(){ 29 cout<<"my2gouzao"<<endl; 30 } 31 My2::~My2(){ 32 cout<<"my2xigou"<<endl; 33 } 34 35 int main(){ 36 My2 my2; 37 my2.say(); 38 }
例3:在一个类中创建另一个类的实例(接口访问)
1 #include <iostream> 2 using namespace std; 3 class My1{ 4 public: 5 My1(); 6 ~My1(); 7 void setage(int age); 8 void show(); 9 private: 10 int m_age; 11 }; 12 13 class My2{ 14 public: 15 My2(); 16 ~My2(); 17 My1 my1; 18 void say(); 19 }; 20 21 My1::My1(){ 22 cout<<"my1gouzao"<<endl; 23 } 24 My1::~My1(){ 25 cout<<"my1xigou"<<endl; 26 } 27 void My1::setage(int age){ 28 m_age=age; 29 } 30 void My1::show(){ 31 cout<<"我今年"<<m_age<<"岁"<<endl; 32 } 33 My2::My2(){ 34 cout<<"my2gouzao"<<endl; 35 } 36 My2::~My2(){ 37 cout<<"my2xigou"<<endl; 38 } 39 void My2::say(){ 40 my1.setage(2); 41 my1.show(); 42 } 43 44 int main(){ 45 My1 my1; 46 My2 my2; 47 my1.setage(20); 48 my1.show(); 49 my2.say(); 50 my1.show(); 51 }
这里用到了私有属性和封装。在My2中定义My1的实例,My1 my1和My2 my2中的my1是不同的,通过my2不能直接修改My1 my1属性的值
参考:
https://www.cnblogs.com/prettyshuang/p/5427689.html
https://www.cnblogs.com/haoyul/p/7287681.html
https://www.cnblogs.com/ljygoodgoodstudydaydayup/p/3854914.html