Chapter 10 Operator Overloading
- 重载为成员函数
双目:
class ClassName
{
public:
DataType operator@(Parameter List); …
};
DataType ClassName::operator@ (Parameter List) { … }
aa@bb //or aa . operator @ (bb)
单目:
class ClassName
{
public:
DataType operator@( ); …
};
DataType ClassName::operator@ ( ) { … }
@aa //or aa.operator @ ( )
默认为前置
Complex operator ++ ( );
后置的话形参列表里有一个int,本身无作用只是为了区分
Complex Complex∷operator ++ ( int )
c2=c1++; //or c2=c1.operator++(0);
- 重载为友元函数
class ClassName
{
public:
friendDataType operator@(Parameter List); …
};
DataType operator@ (Parameter List) { … }
aa@bb //or operator @ (aa , bb)
默认为前置Complex operator ++ (Complex &c )
后置的话同理Complex operator ++ (Complex & c, int )
- 重载为成员函数:
双目运算符参数列表有一个参数,单目运算无参数
重载为友员函数:
双目运算符参数列表有两个参数,单目运算有一个参数
- Rules for Operator Overloading
can not define newoperators
can not change the numberof operands
can not change the precedence
can not change the associativity(结合性)
can not have default parameters “=”, “( )”, “[ ]”
can only be overloaded as member functions “.”, “.*”, “::”, “sizeof”, “?:” can not be overloaded
- 重载赋值运算符
ClassName&ClassName::operator =( const ClassName & source )
{
real= source.real; imag= source.imag; return *this; //注意返回值
}
- 重载输入输出运算符
重载为友元函数 friend ostream & operator <<(ostream & , ClassName & );
ostream & operator <<(ostream & , ClassName & )
{
output<<“( ”<<c.real<<“ , ” <<c.imag<<“i )” <<endl;
return output;//注意返回值
}
friend istream & operator >>(istream & , ClassName & );
istream & operator >>(istream & input, Complex &c)
{
cout<<“Input the real part and” <<“imaginary part of a” <<“complex number:”; input>>c.real>>c.imag;
return input;
}
- 强制类型转换?
class ClassName{ public: operator DataType( ); … }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
2020-07-02 Linux入门-文件管理
2020-07-02 Linux入门-用户管理
2020-07-02 Linux入门-命令行操作初探