[C + +] C + + overload operator = must be a nonstatic member function?

code

#include <iostream>
using namespace std;

class C {
public:
    int x;
    C () {}
    C(int a) : x(a) {}
    //  member function
    C operator = (const C&);
};

C C::operator= (const C& param) {
    x = param.x;
    return *this;
}

int main()
{
    C foo(1);
    cout <<"foo.x = " << foo.x << endl;

    C bar;
    bar = foo;
    cout <<"bar.x = " << bar.x << endl;
    return 0;
}

run

foo.x = 1
bar.x = 1

ERROR

opeartor= must be a nonstatic member function

note

quote

Notice that some operators may be overloaded in two forms: either as a member function or as a non member function
many operators can be overloaded as member function or non member function

explain

The so-called member function is shown in the code section. There is a simple declaration about the operator to be overloaded in the class definition, such as:

    C operator = (const C&);

Here the operator = (equal sign) is overloaded;

In contrast, non member function does not exist in the class definition. For example, the complete definition of a class consists of the following:

class D {
public:
    int y;
    D () {}
    D (int b) : y(b) {}
};

There are many operators in C + +, such as = (equal sign), which can only be overloaded as member function. In other words, they must be declared in the class definition. See code;

At the same time, some operators, such as + (plus sign), can be overloaded as both member function and non member function.

doubt

The example code in the part of toturial [1] classes (II) / the keyword this that I read is as follows:

CVector& CVector::operator= (const CVector& param)
{
  x=param.x;
  y=param.y;
  return *this;
}

Note that it is written as cvector & amp; , referring to the class C , then for = (equal sign), it should be written as C & amp; , but in this way, the compiler (Dev C + + ISO C + + 11) will report an error and modify it to the final code before it can be compiled. This is the inconsistency between the current code and the example code.

reference

Classes (II)
http://www.cplusplus.com/doc/tutorial/templates/

Read More: