c++构造函数中调用构造函数—匿名对象再探

1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 class Copy_construction {
 5 public:
 6     Copy_construction(int a,int b,int c)
 7     {
 8         this->a = a;
 9         this->b = b;
10         this->c = c;
11         cout << "这是Copy_constructiond的有3个默认参数的构造函数!  "<<this->a<<" "<<this->b<<" "<<this->c<<endl;
12     }
13 
14     Copy_construction(int a, int b)
15     {
16         this-> a= a;
17         this->b = b;
18         Copy_construction(3, 4, 5);
19         cout << "这是Copy_constructiond的有2个默认参数的构造函数!  " << this->a << " " << this->b << endl;
20     }
21     ~Copy_construction()
22     {
23         cout << "Copy_construction对象被析构了! "<<this->a << " " << this->b << " " << this->c << endl;
24     }
25 
26     int getC()
27     {
28         return c;
29     }
30 private:
31     int a;
32     int b;
33     int c;
34 
35 };
36 
37 
38 int run()
39 {
40     Copy_construction aa(1, 2);
41     cout << aa.getC() << endl; //c的值为垃圾值,因为匿名对象被创建有立即析构了                                  //就算用不析构的方式,也是垃圾值,因为c是不同对象中的元素                    //在2个参数的构造函数中,没有显式初始化c,不能通过构造其他对象而在本构造对象中访问未初始化的数据
42     return 0;
43 }
44 int main()
45 {
46     
47     run();
48     cout << "hello world!n";
49     return 0;
50 }

如果直接显示调用构造函数,要看怎么去接这个函数, Copy_construction(1,2,3);调用之后马上执行析构匿名对象, Copy_construction  T= Copy_construction(1,2,3)此时匿名对象不析构而直接转正成T。NOTE:构造函数中调用构造函数是危险的做法。

原文链接: https://www.cnblogs.com/yangguang-it/p/6414834.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/249591

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月14日 上午3:48
下一篇 2023年2月14日 上午3:48

相关推荐