有代码
struct node
{
node(int X , int Y):X(X),Y(Y){};
int X;
int Y;
friend bool operator ==(const node &X, const node &Y);
};
int main()
{
node one(5,5);
node two(5,5);
if ( one == two )
{
cout << " true " << endl;
}
return 0;
}
如果我将运算符 == 声明为
bool node::operator ==(const node &X, constnode &Y)
{
return (X.X == X.Y && Y.X == Y.Y);
}
它需要一个参数,但是当我将其声明为
bool operator ==(const node &X, constnode &Y)
{
return (X.X == X.Y && Y.X == Y.Y);
}
需要两个。我知道由语言定义,第一个定义需要一个参数,因为第二个是 *this。
第二个定义是运算符 == ( global ) 的外部定义,它不绑定(bind)到任何结构,因此它不会在其中传递 *this 。
但它仍然被定义为“友元”,这基本上表明(通过第一个定义)成员函数是其自己类的友元函数。这怎么可能?为什么会编译?
最佳答案
声明为友元的方法实际上不是类的方法,而是类外部的全局函数,与类位于同一命名空间中。
所以下面的内联定义...
struct node
{
node(int X , int Y):X(X),Y(Y){};
int X;
int Y;
friend bool operator ==(const node &lhs, const node &rhs) {
return (lhs.X == rhs.X && lhs.Y == rhs.Y);
}
};
...与...相同
bool operator ==(const node &lhs, const node &rhs)
{
return (lhs.X == rhs.X && lhs.Y == rhs.Y);
}
这就是为什么您的第一个operator==定义对于声明为友元的方法来说不是有效的定义。
如果在类外部定义全局运算符 ==,则实际上仅当全局函数需要访问类的私有(private)成员时才需要友元声明。在您的情况下,这不是必需的,因为 X 和 Y 是公共(public)的。
关于c++ - 友元函数声明为成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42463989/