我想要編寫創建與私處小時和分鐘一類的一些代碼。現在我試圖從一個整數減去另一個類中創建一個新的類。整數減去一類
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;
}
你需要[重載](http://stackoverflow.com/questions/4421706/operator-overloading)類的'operator -'。 – NathanOliver
或者您可以定義一個轉換運算符來將'Foo'轉換爲'int',以及'Foo'構造函數獲得一個'int'。 – Beta
'(1,0)'vs'(0,60)'..這會很有趣。 –