成员函数重载与全局函数重载
利用成员函数实现运算符的重载
*在这里实现 ‘+’ 运算符和 ‘<<’ 运算符的重载。
值得注意的是,‘+’ 用全局函数或成员函数都能实现重载;但 ‘<<’ 只能用全局函数实现重载。
class Complex
{
friend Complex operator +(Complex &c1 , Complex &c2); //友元函数
friend ostream &operator <<(ostream &out, Complex &c);
private:
int m_a;
int m_b;
public:
Complex(int a,int b); //有参构造函数
Complex(); //无参构造函数
void print(); //输出复数函数
};
//利用全局函数来重载 +
Complex operator +(Complex &c1 , Complex &c2)
{
Complex tmp; //不能返回引用 只能返回对象
tmp.m_a = c1.m_a + c2.m_a; //不能直接用私有成员变量 使用友元函数
tmp.m_b = c1.m_b + c2.m_b;
return tmp;
}
//利用全局函数来重载 <<
ostream &operator <<(ostream &out, Complex &c) //全局函数实现<<重载 一定返回引用
{
out<< c.m_a << "+" <<c.m_b << "i";
return out;}
operator +(c1,c2);
c1+c2;
class Complex
{
friend ostream &operator <<(ostream &out,const Complex &c);
private:
int m_a;
int m_b;
public:
Complex(int a,int b);
Complex();
void print();
Complex operator +(Complex &c); //成员函数
ostream &operator <<(ostream &out);
};
//成员函数实现 '+' 重载 比全局函数少一个参数
Complex Complex::operator +(Complex &c)
{
Complex tmp;
tmp.m_a = this->m_a + c.m_a; //返回对象本身 而不是返回引用 因为 + 不能作为左值
tmp.m_b = this->m_b + c.m_b; //若保持c1 c2不变 需要放入另一个tmp里
return tmp;
}
/*
//利用成员函数实现 '+' 的重载 ,有两种方式
Complex Complex::operator +(Complex &c)
{
this->m_a = this->m_a + c.m_a; //返回对象本身 而不是返回引用 因为 + 不能作为左值
this->m_b = this->m_b + c.m_b; //此时值都存放于c1中
return *this;
}*/
c3 = c1+c2;
c1.operator + (c2);
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
· Manus的开源复刻OpenManus初探