运算符重载 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=
。
附带说明:不要重载赋值来表示比较,这会让所有未来的维护者感到困惑。
#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=
。
附带说明:不要重载赋值来表示比较,这会让所有未来的维护者感到困惑。