Copy constructor vs assignment operator in C++

时间:2021-05-23 14:44:17

  Difficulty Level: Rookie

  Consider the following C++ program.

 1 #include<iostream>
2 #include<stdio.h>
3
4 using namespace std;
5
6 class Test
7 {
8 public:
9 Test()
10 {
11 }
12 Test(const Test &t)
13 {
14 cout<<"Copy constructor called "<<endl;
15 }
16 Test& operator = (const Test &t) //仅仅为测试
17 {
18 cout<<"Assignment operator called "<<endl;
19 return *this;
20 }
21 };
22
23 int main()
24 {
25 Test t1, t2;
26 t2 = t1;
27 Test t3 = t1;
28 getchar();
29 return 0;
30 }

  Output:
  Assignment operator called
  Copy constructor called

  Copy constructor is called when a new object is created from an existing object, as a copy of the existing object (see this G-Fact).

  And assignment operator is called when an already initialized object is assigned a new value from another existing object.

  t2 = t1;  // calls assignment operator, same as "t2.operator=(t1);"
  Test t3 = t1;  // calls copy constructor, same as "Test t3(t1);"

  References:http://en.wikipedia.org/wiki/Copy_constructor

  Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

  转载请注明:http://www.cnblogs.com/iloveyouforever/

  2013-11-26  21:23:27