C++ Operator Overloading 運算符重載

index > C++ > Operator Overloading

有些事情好像理所當然,但是又不那麼順利。


構造器()

struct point {
    int x, y;
    point() {} // default constructor
    point (int _x, int _y) {
        x = _x; y = _y;
    }
};

也可以這樣寫:

struct point {
    int x, y;
    point() {} // default constructor
    point (int x, int y): x(x), y(y) {}
};

注* 括號裏的是賦值的參數 好像容易記錯。

小於號 <

struct point {
    int x, y;
    // overloading of < operator
    bool operator<(const point &rhs) const{
        // your main logic for the comparator goes here
        return make_pair(x,y) < make_pair(rhs.x, rhs.y);
    }
};

請要小心弱比較的特性(C++: Strict Weak Ordering),肯定有人疑惑過爲什麼只要定義一個小於號。因爲對三種大小關係可以只用一個來實現,只不過等於的狀態要比較兩次,比如a<bb<a結果都爲假,那麼就判斷爲兩者相等。

如果你在定義嚴格小的過程中,誤用了等號,會導致難以預料的結果。而且很可能自己測試對了,某些樣例過不了。

可以這樣去理解:如果滿足條件的時候,本身這個元素,一定放在另外一個元素之前,則這個條件要返還真。

可能有人會覺得) const {這個孤零零的很奇怪,但是這個是必要的語法結構。尤其是在被用於map或者優先隊列之類key的時候。

<<

注* 必須要全局函數的形式(原理暫略)
reference

struct node {
    int x,y;
    friend ostream & operator << (ostream &out,node &T);
};
ostream & operator << (ostream &out,node &T){
    out<<T.x<<" "<<T.y;
    return out;
}

普通()

好像是有括號的計算是需要的(未證實)

struct node {
    int x,y;
    node operator ()(const node &T){return T;}
};

計算

struct node {
    int x,y;
    node ():x(0),y(0){}
    node (int x,int y):x(x),y(y){}
    int len(){return x*x+y*y;}
    node operator - (const node &T){return node(x-T.x,y-T.y);}
    node operator + (const node &T){return node(x+T.x,y+T.y);}
    int operator * (const node &T){return x*T.x+y*T.y;}
    int operator / (const node &T){return x*T.y-y*T.x;}//叉積
};

例題

一般都是在座標運算,或者比較特殊的模擬的時候需要用到這些。
CodeForces - 136D :: Mine :: Dalao

參考

Using Constructors and comparison function in C++ By PraveenDhinwa

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章