C++类构造析构基础
一、相关内容
- 模块中栈对象(类对象),先申请后释放;
- 嵌套对象,先申请成员对象再申请外部对象,释放时先释放外部对象,再释放成员对象;
二、栈对象申请释放
2.1同级别栈对象申请释放
结果:
1 2 create MyClassA 3 create MyClassB 4 Hello World! 5 delete MyClassB 6 delete MyClassA 7 8
代码(W32 控制台程序):
1 #include <iostream> 2 3 class MyClassA 4 { 5 public: 6 MyClassA(); 7 ~MyClassA(); 8 9 private: 10 11 }; 12 13 MyClassA::MyClassA() 14 { 15 std::cout << "create MyClassA" << std::endl; 16 } 17 18 MyClassA::~MyClassA() 19 { 20 std::cout << "delete MyClassA" << std::endl; 21 22 } 23 24 class MyClassB 25 { 26 public: 27 MyClassB(); 28 ~MyClassB(); 29 30 private: 31 32 }; 33 34 MyClassB::MyClassB() 35 { 36 std::cout << "create MyClassB" << std::endl; 37 38 } 39 40 MyClassB::~MyClassB() 41 { 42 std::cout << "delete MyClassB" << std::endl; 43 44 } 45 46 int main() 47 { 48 MyClassA a; 49 MyClassB b; 50 std::cout << "Hello World!\n"; 51 } 52
2.2嵌套对象申请释放
结果:
1 2 create MyClassA 3 create MyClassB 4 Hello World! 5 delete MyClassB 6 delete MyClassA
代码:
1 #include <iostream> 2 3 class MyClassA 4 { 5 public: 6 MyClassA(); 7 ~MyClassA(); 8 9 private: 10 11 }; 12 13 MyClassA::MyClassA() 14 { 15 std::cout << "create MyClassA" << std::endl; 16 } 17 18 MyClassA::~MyClassA() 19 { 20 std::cout << "delete MyClassA" << std::endl; 21 22 } 23 24 class MyClassB 25 { 26 public: 27 MyClassB(); 28 ~MyClassB(); 29 30 MyClassA a; 31 32 private: 33 34 }; 35 36 MyClassB::MyClassB() 37 { 38 std::cout << "create MyClassB" << std::endl; 39 40 } 41 42 MyClassB::~MyClassB() 43 { 44 std::cout << "delete MyClassB" << std::endl; 45 46 } 47 48 int main() 49 { 50 MyClassB b; 51 std::cout << "Hello World!\n"; 52 } 53
三、相关参考
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。