2014-11-05 73 views
1

我有兩個文件:沒有運營商 「<」 匹配這些操作數的操作數類型是:雙<my_class

my_header.h

class my_class { 
public: 
    my_class(); 

    my_class(long long number); 

    my_class(int number); 

    my_class(double number); 

    bool operator<(const my_class& rhs) const; 

    ////// 
} 

my_class.h

my_class::my_class() 
{ 
    //implementation 
} 

my_class::my_class(long long number) 
{ 
    //implementation 
} 

my_class::my_class(int number) 
{ 
    //implementation 
} 

my_class::my_class(double number) 
{ 
    //implementation 
} 

bool my_class::operator<(my_class const& rhs) const 
{ 
    //implementation 
} 

我不明白,我錯了。我超載運算符<。另外,我有constructordouble類型。

當然,此外,我執行其他5個運營商(==, !=, >, <=, =>this scheme。其他運算符在同一個命名空間中,但它們不是成員函數。

測試用例

my_class a = 2; 
bool check = 5.17 < long_int1; 
+1

提供一個自由函數'布爾運算符<(雙LHS ,my_class const&rhs)'或者從double創建一個臨時的'my_class'。 – clcto 2014-11-05 22:30:02

+0

可能重複的[運算符重載:成員函數與非成員函數?](http://stackoverflow.com/questions/4622330/operator-overloading-member-function-vs-non-member-function) – 2014-11-05 22:31:05

+0

clcto,爲什麼我必須提供這個功能?實際上,我有雙重構造函數,爲什麼C++不會執行double - > my_class? – Denis 2014-11-05 22:31:38

回答

1

C++規則禁止使用隱式轉換來創建要在其上調用成員函數的對象 。因此,和 對象支持隱式轉換時,通常將二進制 運算符定義爲非成員(如果需要,爲朋友)。對於 運算符的比較,我有一個簡單的模板基類,它將提供它們, 前提是我的類有一個成員函數compare,並從中繼承。

template <typename T> 
class ComparisonOperators 
{ 
    friend bool operator==(T const& lhs, T const& rhs) 
    { 
     return lhs.compare(rhs) == 0; 
    } 
    friend bool operator!=(T const& lhs, T const& rhs) 
    { 
     return lhs.compare(rhs) != 0; 
    } 
    friend bool operator<(T const& lhs, T const& rhs) 
    { 
     return lhs.compare(rhs) < 0; 
    } 
    // and so on. 
}; 

你寫這一次,然後所有你需要做的就是提供一個(成員) 功能,並從中得出:

class MyClass : public ComparisonOperators<MyClass> 
{ 
public: 
    int compare(MyClass const& other) const 
    { 
     // return <, == or > 0, according to whether this is 
     // <, == or > other. 
    } 
} 
+0

我是對的,在MyClass :: compare函數中,我必須在'(* this)'和'other'之間計算'diff',然後我必須比較'diff'和'0'? – Denis 2014-11-05 23:49:47

+0

@Denis如果'* this'應該在'other'之前排序,等於0'* this'應該被認爲是相等的,那麼你必須做任何必要的事情來返回一個小於0的int值到'other',如果'* this'應該被認爲大於'other',則大於0。這在實踐中意味着什麼取決於對象中的實際數據類型以及如何定義關係。 – 2014-11-06 09:56:19

+0

感謝您的幫助! – Denis 2014-11-06 11:18:21

0

的問題是,編譯器無法知道要隱式轉換5.17my_class實例的方式。想想看,如果你有兩個不同的類可以接受double作爲唯一的構造函數參數,會發生什麼。有兩種解決方法。

  1. 提供轉換運算符。這將允許編譯器將my_class的實例作爲double讀取。
  2. 切換參數的順序。 !(my_class > 5.17)應該可以正常工作。
+0

我做了什麼,如果my_class不能轉換爲double,並且我不能切換參數的順序? – Denis 2014-11-05 23:10:20

+0

如果你做了一個比較,那麼比較必須爲你的課程計算一個「價值」,並將其與5.17進行比較。這個「值」可以由轉換操作符返回。你怎樣才能不改變參數?只是代碼可讀性? – 2014-11-05 23:13:58

+0

我的對象可以更多,然後MAX_DOUBLE。我不切換參數,因爲此代碼是由外部系統測試的。 – Denis 2014-11-05 23:16:04

相關問題