Copy constructor calls time

C ++ copy constructor called as soon as there are 3

1. Place an object that has been created to initialize another object

. 1      STU S2 ( 10 ); // with a reference constructor calls 
2      STU S3 (S2); // copy constructor call 
. 3      COUT << " S2 IS Age " << endl << s2.s_age;

 

2. The value passed to the function by value way

 1 void work(stu s)
 2 {
 3     
 4 }
 5 void test01()
 6 {
 7     stu s;
 8     work(s);
 9 }
10 int main()
11 {
12     //test();
13     test01();
14     return 0;
15 }

3. The local object returned by value

 1 stu go()
 2 {
 3     stu p1;
 4     cout << (int*)&p1 << endl;
 5     return p1;
 6 }
 7 
 8 void test02()
 9 {
10     stu w = go();
11     cout << (int*)&w << endl;
12 }
13 int main()
14 {
15     //test();
16     //test01();
17     test02();
18     return 0;
19 }

The complete code

. 1 #include <bits / STDC ++ H.>
 2  the using  namespace STD;
 . 3  
. 4  class STU
 . 5  {
 . 6      public :
 . 7          STU ()
 . 8          {
 . 9              the puts ( " STU no argument constructor calls " ); 
 10          }
 . 11          
12 is          STU ( int Age)
 13 is          {
 14              s_age = Age;
 15              the puts ( " STU has argument constructor calls " );
 16          }
. 17          
18 is          STU ( const STU & S)
 . 19          {
 20 is              // all the property of the incoming copy all students to me 
21 is              s_age = s.s_age;
 22 is              the puts ( " STU copy constructor calls " );
 23          }
 24          ~ STU ()
 25          {
 26 is              the puts ( " STU destructor calls " );
 27          }
 28          int s_age;
 29  };
 30  // call 
31 is  void Test ()
32  {
 33 is  
34 is      STU S2 ( 10 ); // with a reference constructor calls 
35      STU S3 (S2); // copy constructor call 
36      COUT << " S2 IS Age " << s2.s_age << endl;
 37 [      COUT << " S3 IS Age " << s3.s_age << endl;
 38 is  }
 39  
40  void Work (STU S)
 41 is  {
 42 is      
43 is  }
 44 is  void Test01 ()
 45  {
 46 is      STU S;
 47      Work (S);
48 }
49 
50 stu go()
51 {
52     stu p1;
53     cout << (int*)&p1 << endl;
54     return p1;
55 }
56 
57 void test02()
58 {
59     stu w = go();
60     cout << (int*)&w << endl;
61 }
62 int main()
63 {
64     //test();
65     //test01();
66     test02();
67     return 0;
68 }
View Code

 

Guess you like

Origin www.cnblogs.com/mch5201314/p/11584004.html