2011-10-04 171 views

回答

2

通常要超載全球操作:

Point operator+(Point const &a, float b); 
Point operator+(float a, Point const &b); 

相反的兩個重載,您可能只想使用一個過載:

Point operator+(Point const &a, Point const &b); 

,然後有一個構造函數來創建一個浮動一點:

class Point { 
    public: 
     Point(float); 
}; 

在這種情況下,增加了浮動的點將使用構造函數的浮動轉換爲一個點,然後使用您的重載運算符+將這兩個點一起添加。

+1

的確。但許多人(例如Meyers)會認爲隱式轉換構造函數會導致問題... –

+0

@OliCharlesworth:他們肯定會*導致一些問題,但是當您仔細觀察時,當您從類轉換爲基本類型時,它們經常出現類型。從基本類型到班級*往往會更安全(儘管它肯定會*仍然會引發問題)。 –

+0

特別是在這種情況下:'point + 10'已經結合了矢量和標量值的數學概念,允許用戶寫'10'來代替'point_offset(10,10,10)'(注意點和向量值也略有不同 - 向量可以用來表示相對於原點的點,但並非所有的向量*都是*點,並且在「將兩個點相加在一起」在數學上沒有意義)。如果你要將這些概念結合起來,那麼對我而言,允許隱式轉換是有意義的。如果你不想合併它們,不要允許'Point + float'。 –

2

作爲一個自由的功能:

Point operator+(float other, const Point &pt) { 
    return pt+other; 
} 
1

外班的:

inline Point operator+(const float& other, const Point& pnt) { return Point(...); }; 
2

鑑於現有Point& Point::operator+=(float other),添加這兩個免費功能:

Point operator+(Point pt, float other) { 
    return pt += other; 
} 
Point operator+(float other, Point pt) { 
    return pt += other; 
}