运算符重载运算符 = 使用友元函数
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=
作为非成员。
作为旁注:不要将分配重载为意味着比较,这会让所有未来的维护者感到困惑。
相关文章:
- 模板类无法识别友元运算符
- 类模板中文本运算符的友元声明
- 运算符重载在 C++ 中使用友元函数
- 模板化类的嵌套类中的友元运算符
- 为什么T是未定义的?我正在尝试实现一个用于双链表的节点类,它不喜欢我使用友元运算符后的T
- 为什么我不能定义一元运算符,然后在 MSVC 的模板类中声明具有相同名称的友元二进制运算符?
- C++模板内部类友元运算符重载
- 不能在友元函数中使用重载运算符
- 使用shared_ptr向量重载 ostream 友元运算符
- 使用模板类重载的友元运算符
- 尝试重载模板类友元<<运算符时出错
- 使用友元函数重载新运算符
- 为什么重载运算符时需要友元关键字<<
- 我的运算符重载友元函数无法理解模板类型 T 的问题
- 友元运算符中的变量范围
- 为什么友元运算符<<在某些情况下使用,而在其他情况下不使用
- 如何在局部类中定义友元函数运算符>>?
- C++以友元身份重载 ostream 运算符会导致错误:变量在此上下文中是私有的
- 动态数组模板类:ostream&运算符友元函数的问题
- 运算符<<友元函数和模板