运算符重载运算符 = 使用友元函数

Operator overloading of operator= using friend function

本文关键字:运算符 友元 函数 重载      更新时间:2023-10-16
#include<iostream>
using namespace std;
class a
{
    int x;
    int y;
    public:
    void get_xy(int x,int y)
    {
        this->x=x;
        this->y=y;  
    }   
    friend int operator=(a,a);
};
int operator=(a a5,a a6)
{
    if(a5.x==a6.x&&a5.y==a6.y)
    {
        return(1);
    }
    else
    {
        return 0;
    }
}
int main()
{
    a a1,a2;
    a1.get_xy(5,4);
    a2.get_xy(5,4);
    if(a1=a2)
    {
        cout<<"y"<<endl;
    }
    else
    {
        cout<<"n"<<endl;
    }
    return 0;
}

我正在尝试通过使用friend函数来重载分配operator=,并在附加的屏幕截图中遇到错误。但是,当我使用成员函数重它时,它会按预期工作。代码发布在上面。

C++11 13.5.3/1:

An assignment operator shall be implemented by a non-static member function with exactly one parameter...

因此,该标准只是断然禁止超载operator=作为非成员。

作为旁注:不要将分配重载为意味着比较,这会让所有未来的维护者感到困惑。