Here is my code which I expect to output "Assignment" but getting both "copy" and "Assignment ".
#include <iostream>
using namespace std;
class Test
{
public:
Test(){}
Test(Test &t){ cout<<"\n copy ";}
void operator = (Test t) {cout<<"\n Assignment ";}
};
void main()
{
Test t1; //default ctor
Test t3;
t3=t1; //Assignment
}
If I change my code to
void operator = (Test &t) {cout<<"\n Assignment ";}
I get expected ouput only "Assignment".
What is the difference in both?
The difference is that the argument Test t
passes t
by value . That invokes the copy constructor to create a separate local copy that you can use within the function.
When you use Test &t
(note that it should have been const Test &t
), you are passing a reference to the original value, thus avoiding copying.
Notes:
the correct signature of an assignment operator is this (satisfy the return value by return *this;
):
Test & operator = (const Test &t);
the correct signature for copy constructor is this:
Test(const Test &t);
void operator=(Test t) { ... }
Expects the argument by value. The argument t
is constructed by using the copy constructor.
void operator=(Test& t) { ... }
expects the argument by reference. The reference is an alias to the object used to call the function. Hence, it does not create a new object.
When you do following:
operator = (Test t)
compiler makes a copy of t1 to create t3....
you mean passing a reference of Test instead of a copy....
do
void operator = (Test& t) { cout << "\n Assignment "; }
instead of
void operator = (Test t) { cout << "\n Assignment "; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.