使成员函数成为朋友
当你让一个类的成员函数成为它自己的友元时会发生什么!?
下面的代码编译并运行。如果没有友元声明,就会生成“操作符的参数太多”(这是正确的)。我意识到这样做没有任何意义,但有人能告诉我这里发生了什么吗?朋友是否强制编译器以某种方式省略默认的 this 参数?
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;
}
What happens when you make a member function 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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不同之处在于,即使整个定义出现在类中,友元也不是成员;相反,该函数被放置在周围的命名空间中。因此,不存在
this
指针。虽然成员operator<
对this
和显式右侧参数进行隐式操作,但friend
需要左侧和右侧参数侧面参数显式提供为函数参数 - 因此是额外的参数。您的friend
版本相当于将函数放在类之后,只不过它可以访问private
和protected
成员和基类,并且是隐式的inline
(尽管这并不意味着编译器必须内联它 - 这只是一个提示,但对于单一定义规则来说很重要,因为您的friend
函数可以从许多翻译单元中包含并且链接没有问题)。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 memberoperator<
operates implicitly onthis
and the explicit right-hand-side argument, afriend
needs both left- and right-hand side argument provided explicitly as function parameters - hence the extra parameter. Yourfriend
version is equivalent to putting the function after the class, except that it has access to theprivate
andprotected
members and bases and is implicitlyinline
(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 yourfriend
function can be included from many translation units and link without issues).这没有任何意义。类的成员函数如何成为同一个类的友元?
您已将
operator <
重载为友元函数(而不是成员函数)。在类中提供友元函数的定义(主体)是合法的。然而,在其定义中使用this
是非法的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 usethis
inside its definition