成員函式過載與全域性函式過載
利用成員函式實現運算子的過載
*在這裡實現 ‘+’ 運算子和 ‘<<’ 運算子的過載。
值得注意的是,‘+’ 用全域性函式或成員函式都能實現過載;但 ‘<<’ 只能用全域性函式實現過載。
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);