why assigment operator can not be frined function
why assigment operator can not be frined
this is a problem in my work and I have find th solution on stackoverflow,so recorder here
problem description
When I refactor my object, I have a problem which need to change the return value
of and function std::string to a struct data, but I don’t want to change my code
where the function be used, so I want to overload the assignment operator which
will assign a struct to string.The code is as follows:
|
|
when I compile this file , this is an error follows:
|
|
why does this happen?
Firstly, it should be noted that this has nothing to do with the operator being implemented as a friend specifically. It is really about implementing the copy-assignment as a member function or as a non-member (standalone) function. Whether that standalone function is going to be a friend or not is completely irrelevant: it might be, it might not be, depending on what it wants to access inside the class.
Now, the answer to this question is given in D&E book (The Design and Evolution of C++). The reason for this is that the compiler always declares/defines a member copy-assignment operator for the class (if you don’t declare your own member copy-assignment operator).
If the language also allowed declaring copy-assignment operator as a standalone (non-member) function, you could end up with the following
|
|
As seen in the above example, the semantics of the copy-assignment would change in the middle of the translation unit - before the declaration of your standalone operator the compiler’s version is used. After the declaration your version is used. The behavior of the program will change depending on where you put the declaration of your standalone copy-assignment operator.
This was considered unacceptably dangerous (and it is), so C++ doesn’t allow copy-assignment operator to be declared as a standalone function.
It is true that in your particular example, which happens to use a friend function specifically, the operator is declared very early, inside the class definition (since that’s how friends are declared). So, in your case the compiler will, of course, know about the existence of your operator right away. However, from the point of view of C++ language the general issue is not related to friend functions in any way. From the point of view of C++ language it is about member functions vs. non-member functions, and non-member overloading of copy-assignment is just prohibited entirely for the reasons described above.
Solution
due to the solution above is not proper.So I overWrite the orignal function, and
invoke different version in their needed place.