开发者

Making a member function a friend

开发者 https://www.devze.com 2023-01-28 07:40 出处:网络
What happens when you make a member fu开发者_StackOverflow中文版nction of a class a friend of itself!?

What happens when you make a member fu开发者_StackOverflow中文版nction of a class a friend of itself!?

The code below compiles and runs. Without the friend declaration a 'too many arguments to operator' is generated (and rightly so). I realise that doing this doesn't make any sense but can anyone tell me what is happening here? Does friend force the compiler to omit the default this parameter in some way?

class Test
{
public:
  friend bool operator<(Test& lhs, Test& rhs)
  {
     return true;
  }
};

int main( int c, char** argv)
{
  Test test1;
  Test test2;

  return test1 < test2;
}


The difference is that a friend is not a member even if the entire definition appears inside the class; rather, the function is placed in the surrounding namespace. So, there is no this pointer. While a member operator< operates implicitly on this and the explicit right-hand-side argument, a friend needs both left- and right-hand side argument provided explicitly as function parameters - hence the extra parameter. Your friend version is equivalent to putting the function after the class, except that it has access to the private and protected members and bases and is implicitly inline (though that doesn't mean the compiler has to inline it - it's only a hint, but it's important with respect to the One Definition Rule in that your friend function can be included from many translation units and link without issues).


What happens when you make a member function of a class a friend of itself!?

That doesn't make any sense. How can a member function of a class be a friend of the same class?

You have overloaded operator < as a friend function (not as a member function). Providing the definition(body) of a friend function inside the class is legal. However it is illegal to use this inside its definition

friend bool operator<(Test& lhs, Test& rhs)
{
     *this ; //error
     return true;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消