Operator override - when to use friend?

六月ゝ 毕业季﹏ 提交于 2019-12-14 02:08:35

问题


I'm wondering why the () operator override can't be "friend" (and so it needs a "this" additional parameter) while the + operator needs to be friend like in the following example:

class fnobj
{
    int operator()(int i);
    friend int operator+(fnobj& e);
};

int fnobj::operator()(int i)
{

}

int operator+(fnobj& e)
{

}

I understood that the + operator needs to be friend to avoid the "additional" extra this parameter, but why is that the operator() doesn't need it?


回答1:


You have overloaded the unary plus operator. And you probably didn't want to do that. It does not add two objects, it describes how to interpret a single object when a + appears before it, the same as int x = +10 would be interpreted. (It's interpreted the same as int x = 10)

For the addition operator, it is not correct that "the + operator needs to be friend".

Here are two ways to add two fnobj objects:

int operator+(fnobj& e);
friend int operator+(fnobj& left, fnobj& right);

In the first form, this is presumed to be the object to the left of the +. So both forms effectively take two parameters.

So to answer your question, instead of thinking that "operator() doesn't need friend", consider it as "operator() requires this" Or better still, "Treating an object as a function requires an object".




回答2:


You didn't understand this correctly (and aren't using it correctly as well).

There are two ways in C++ to define a binary operator for a class, either as a member function

class A
{
public:
    int operator+ (A const& other);
};

or as a free function

class A {};

int operator+ (A const& lhs, A const& rhs);

What you are currently mixing up is that you can declare and define this free function in the class scope as friend, which will allow the function to use private members of the class (which is not allowed in general for free functions).



来源:https://stackoverflow.com/questions/12764696/operator-override-when-to-use-friend

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!