簡體   English   中英

使用好友函數對operator =進行運算符重載

[英]Operator overloading of operator= using friend function

#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=作為非成員進行重載。

另外請注意:不要重載分配以進行比較,這會使所有未來的維護人員感到困惑。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM