過載operator 的注意事項

2021-08-21 06:47:10 字數 917 閱讀 3789

#include

#include

#include

using

namespace

std;

template

<

class

type, int

dim>

class

point

}type&

operator(

int index)

type

operator(

int index)

const

private:

type _coords[dim];

};template

<

class

type, int

dim>

ostream& operator

<<(ostream &os, const point&pt)

一開始挺不明白為何過載operator兩次,而且二者的區別僅有返回值和函式宣告const與非const的區別。

intmain

()

;point<

string,

3> p(s);

cout

<< p;

}最終結果發現只有第二個過載函式被呼叫,即const的那乙個。我注釋掉第二個過載函式,執行,編譯器報錯:error c2678: 二進位制「[」: 沒有找到接受「const point」型別的左運算元的運算子(或沒有可接受的轉換)。

1、請注意operator下標操作符只能作為類的成員函式,同時在定義類的下標操作符時請定義兩個版本,以適應const物件和非const物件

2、小心operator帶來的陷阱。在過載時必須把這部分陷阱考慮進去,以防止此付出的代價。

operator 過載 注意事項

進行類的運算操作符過載時,需要把涉及到的運算子過載的類的標頭檔案包含近年來,例如 include 如果沒有包含上面標頭檔案,則下面的類進行operator 過載時會出現編譯錯誤 binary no operator found which takes a right hand operand of ...

QT PaintEvent過載後注意事項

paintevent繼承過載可以實現自定義功能。子類繼承paintevent 後原定義的樣式需要在paintevent 裡重新呼叫畫刷 void mimageview paintevent qpaintevent event 注意事項 void mimageview paintevent qpain...

函式過載的注意事項 必看

include iostream using namespace std void func const int a void func int a int main 上面 中func a 呼叫那個過載函式呢?呼叫函式的優先順序取決於 傳入引數的型別與那個過載函式形參最接近 函式過載狀態一 void...