1. 程式人生 > >【C++】學習筆記草稿版系列11(運算子過載)

【C++】學習筆記草稿版系列11(運算子過載)

運算子過載和友元之間是如何發生關係的

友元過載,成員過載
單目和雙目運算子可以過載
通常情況下:
雙目運算子過載為成員的話需要一個引數,過載為友元的話需要兩個引數

const Complex operator+(Complex& another);
friend Complex operator+(Complex & a, Complex & b);

單目運算子過載為成員的話需要0個引數,過載為友元的話需要1個引數。
不必過載的運算子(= &)

// 運算子過載
class Complex
{
public:
    Complex(float
x = 0, float y = 0) :_x(x), _y(y){} void dis() { cout<<"("<<_x<<", "<<_y<<")"<<endl; } friend Complex operator+(Complex & a, Complex & b); Complex operator+(Complex & another); private: float _x; float _y; }; Complex operator
+(Complex & a, Complex & b) { Complex t; t._x = a._x + b._x; t._y = a._y + b._y; return t; } Complex Complex::operator+(Complex & another) { Complex t; t._x = this->_x + another._x; t._y = this->_y + another._y; return t; } int main() { Complex c1(1
, 2), c2(2, 3); Complex c = c1 + c2; c1.dis() c2.dis() c.dis() return 0; }
class Complex
{
public:
    Complex(float x = 0, float y = 0)
        :_x(x), _y(y){}
    void dis()
    {
        cout<<"("<<_x<<", "<<_y<<")"<<endl;
    }
    Complex & operator+=(const Complex & another);
    Complex operator-()
    {
        return Complex(-this->_x, -this->_y);
    }
private:
    float _x;
    float _y;
};

Complex & Complex::operator+=(const Complex & another)
{
    this->_x += another._x;
    this->_y += another._y;

    return *this;
}

流輸入輸出運算子過載

希望能夠實現的情況

Complex c(1, 2);
cout<<c<<endl;
//cout是一個流物件,ostream型別,<<是一個雙目運算子
//不能實現:cout.operator<<(x)
//可以實現:operator<<(cout, c)

類段的程式碼

class Complex
{
public:
    Complex(float real = 0, float image = 0)
        :_x(real), _y(image){}
    void dis()
    {
        cout<<"("<<_x<<", "<<_y<<")"<<endl;
    }
    friend ostream & operator<<(ostream & os, const Complex &c)
    {
        os<<"("<<c._x<<", "<<c._y<<")"<<endl;
        return os;
    }
    friend istream & operator<<(istream & is, Complex &c)
    {
        is>>c._x>>c._y;
        return is;
    }
private:
    float _x;
    float _y;
};

流輸入輸出運算子過載

istream & operator>>(istream &, 自定義類 &);
ostream & operator<<(ostream &, 自定義類 &);

不可過載的運算子

. ——成員訪問運算子
.*——成員指標訪問運算子
::——域運算子
sizeof——長度運算子
?:——條件運算子

注意事項

  1. 一個操作符的左右運算元不一定是相同型別的物件,這就涉及到將該操作符函式定義為誰的友元,誰的成員問題。
  2. 一個操作符函式,被宣告為哪個類的成員,取決於該函式的呼叫物件(通常是左運算元)。
  3. 一個操作符函式,被宣告為哪個類的友元,取決於該函式的引數物件(通常是右運算元)。