1. 程式人生 > >Qt中C++運算子過載

Qt中C++運算子過載

1 背景

    在Qt中QPoint只支援二維的整型座標,由於專案需要支援三維的浮點型座標,因此我仿照QPoint自定義一個類QPoint3D,其中涉及到了運算子過載的問題。

2 過載方法

    參考資料[1]提到,C++中運算子過載有兩種方式:成員函式友元函式。在Qt原始碼中,使用的是後者,下面是QPoint.h的部分程式碼:

friend Q_DECL_CONSTEXPR inline bool operator==(const QPoint &, const QPoint &);
friend Q_DECL_CONSTEXPR inline bool operator!=(const QPoint &, const QPoint &);
friend Q_DECL_CONSTEXPR inline const QPoint operator+(const QPoint &, const QPoint &);
friend Q_DECL_CONSTEXPR inline const QPoint operator-(const QPoint &, const QPoint &);

3 疑問

    友元的實現是不是要和類的定定義在同一個檔案中才能使得過載運算子宣告能夠找到對應的實現呢?答案是否定的,友元函式可以在任意位置實現(其實QPoint.h中也只是聲明瞭過載運算子而已,並沒有相關實現)。

4 備註

    對於三維座標點的表達,如果不想自定義QPoint3D的,可以使用QVector3D,其實它就是一個QPoint3D!

參考資料