c and c++ assignment (overloaded = operator)
- 2020-06-07 05:01:28
- OfStack
First of all, the various operators in c++ are implemented as functions, such as =, which is the equal sign function.
So when you assign a value to an object with the = sign, you're actually calling the function with the = sign.
Analyze the following code
#include <iostream>
using namespace std;
class Test{
public:
explicit Test(){
data = 0;
}
explicit Test(int d):data(d){
cout << "C:" << this << ":"<< this->data << endl;
}
// Copy constructor
Test(const Test &t){
cout << "Copy:" << this << endl;
data = t.data;
}
// overloading = The operator no.
Test& operator= (const Test &t){
cout << "assign" << this << endl;
if(this != &t){
data = t.data;
}
return *this;
}
~Test(){
cout << "F:" << this << ":" << this->data << endl;
}
private:
int data;
};
int main(){
Test t1(10);
Test t2, t3;
t3 = t2 = t1;
return 0;
}
Focus on the following functions
// overloading = The operator no.
Test& operator = (const Test &t){
cout << "assign" << this << endl;
if(this != &t){
data = t.data;
}
return *this;
}
Analysis:
1. What does operator = mean
2. Why is the parameter a reference type
3. Why is the parameter limited by const
4, Why if(this! = & t) judgment
5. Why is there a return value
6. Why is the return value of type a reference type
Analysis points answer:
Test t2;
t2 = t1; // The actual operation is t2.operator =(t1), so this in the function is t2
1, override the = function of class Test, which will be called when an object of class Test is manipulated with the = sign
2. Avoid calling copy constructors
3. Avoid accidentally modifying the value of the member variable in the parameter t (t.data = 100;)
4. Prevent yourself from assigning values to yourself
5 in order to be able to use t3 = t2 = t1. If there is no return value, then es62EN3.operator =(t2=t1), t2=t1 has no return value, so compile failed.
6, not a reference is ok, using a reference type prevents the old version of the compiler from calling a copy constructor at return, while the new version of the compiler (gcc 4.8.5-20) does not call a copy constructor even without a reference type.
conclusion