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:
构造函数中调用构造函数是危险的做法。
原文:http://www.cnblogs.com/yangguang-it/p/6414834.html