首页 > 其他分享 >成员函数重载与全局函数重载

成员函数重载与全局函数重载

时间:2022-12-05 15:48:58浏览次数:36  
标签:tmp 函数 operator Complex 重载 c2 全局 c1

利用成员函数实现运算符的重载

*在这里实现 ‘+’ 运算符和 ‘<<’ 运算符的重载。

值得注意的是,‘+’ 用全局函数或成员函数都能实现重载;但 ‘<<’ 只能用全局函数实现重载。


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);

 

标签:tmp,函数,operator,Complex,重载,c2,全局,c1
From: https://www.cnblogs.com/uestc-du/p/16952455.html

相关文章