2017-05-15 32 views
-2

我想要編寫創建與私處小時和分鐘一類的一些代碼。現在我試圖從一個整數減去另一個類中創建一個新的類。整數減去一類

class Foo 
{ 
Public: 
    Foo(int u, int m); 
    Foo(int m); 
    int operator-(const Foo& other); 
    friend Foo operator-(int lhs, const Foo& rhs); 

Private: 
    int minute, hour; 
}; 

Foo::Foo(int u, int m): hour(u), minute(m){} 
Foo::Foo(int m): hour(0), minute(m){} 

int Foo::operator-(const Foo& other) 
{ 
    int x; 
    x = (60*(uur-other.uur)); 
    x += (min - other.min); 
    return x; 
} 

main() 
{ 
    Foo t1(2,10); 
    const Foo kw(15); 
    Foo t2(t1 -kw); 
    Foo t3(2,10); 
    Foo t4(132 -t3); 
} 

現在我不能讓T4僅包含2分鐘(132 - ((60 * 2)-10)) 有誰知道如何解決這個問題? 我得到的錯誤: 錯誤:不對應的「操作符 - 」(操作數類型是「廉政」和「富」)

void operator-(int x, const Foo& other); 

當我有這個功能我得到的錯誤 錯誤:「無效美孚:: operator-(int,const Foo &)'必須採用零個或一個參數。 得到它用下面的代碼工作:

Foo operator-(int lhs, const Foo& rhs) 
{ 
    int y; 
    y = lhs - rhs.min; 
    y -= (60 * rhs.uur); 
    return y; 
} 
+3

你需要[重載](http://stackoverflow.com/questions/4421706/operator-overloading)類的'operator -'。 – NathanOliver

+0

或者您可以定義一個轉換運算符來將'Foo'轉換爲'int',以及'Foo'構造函數獲得一個'int'。 – Beta

+0

'(1,0)'vs'(0,60)'..這會很有趣。 –

回答

2

由於錯誤消息說,你需要一個operator-接受一個int作爲其左側參數和Foo作爲其右手的說法。這不能是一個成員函數,因爲成員函數總是把他們自己的類型作爲他們的第一個參數。所以你必須使它成爲一個自由函數:

Foo operator-(int, const Foo&) { ... } 
+0

當我包括: void operator-(int x,const Foo&other); 這個函數我得到了錯誤錯誤:'void Foo :: operator-(int,const Foo&)'必須帶有零個或一個參數 – Dylan

+1

@Dylan根據編輯中的錯誤消息,你似乎已經使它成爲'Foo'。它不應該。正如上面的答案所述,它需要是一個*免費*功能。 –

+0

@ G.M。這是不可能的,因爲分鐘和小時都是私人的。 (int x,const Foo&other)') int y; y = x - other.min; y - =(60 * other.uur); return y; }' – Dylan