2013-11-04 29 views
0

當前輸出是垃圾8位數值。我不太知道爲什麼除了功能不加入1和2 另外,我想如何實現一個功能:C++操作符超載會吐出垃圾值

TrashCan other = combined – myCan; 
cout << "the other cup's filled to " << other.getUsed() << endl; 

下面的代碼:

主:

int main() 

{ 
cout << "Welcome to Howie's TrashCan Program!" << endl; 

TrashCan myCan; 
TrashCan yourCan; 

yourCan.setSize(12); 
myCan.setSize(12); 

yourCan.addItem(); 
yourCan.addItem(); 
myCan.addItem(); 

myCan.printCan(); 
yourCan.printCan(); 

TrashCan combined = yourCan + myCan; 
cout << "this drive's filled to " << combined.getUsed() << endl;... 

類別:

class TrashCan { 
public: 
TrashCan(); 
TrashCan(int size); 
TrashCan(int size, int contents); 
TrashCan operator+(TrashCan); 
TrashCan operator-(TrashCan); 
void setSize(int size); 
void addItem(); 
void empty(); 
void cover(); 
void uncover(); 

void printCan(); 
int getUsed(); 

private: 
bool myIsCovered; 
int my_Size; 
int my_Contents; 
}; 

執行:(我假設我搞砸了一個o F中的以下功能)

TrashCan TrashCan::operator+ (TrashCan A) 
{ 
TrashCan combined; 
combined.my_Contents= my_Contents + A.my_Contents; 
} 

int TrashCan::getUsed() 
{ 
return my_Contents; 
} 
+3

打開提高警戒級別。 – chris

回答

1

你不回臨時在你的函數:

TrashCan TrashCan::operator+ (TrashCan A) 
{ 
TrashCan combined; 
combined.my_Contents= my_Contents + A.my_Contents; 
// should be 
return combined; 
} 
+0

謝謝,這似乎工作。 – user2924131

+0

另外,我將如何實現我已編輯到我的主減法函數? – user2924131

+0

@ user2924131完全一樣的方式。我懷疑在設置結果對象「組合」時,你需要在操作員中做更多的事情。具體來說,您可能需要對'size'和'isCovered'成員進行調整,但按照這種模式,您應該沒問題。 *這兩種操作都不需要修改「A」或「* this」。 – WhozCraig

-1

試圖改變這種

TrashCan TrashCan::operator+ (TrashCan A) 
{ 
    TrashCan combined; 
    combined.my_Contents= my_Contents + A.my_Contents; 
} 

有了這個

TrashCan TrashCan::operator+ (TrashCan A) 
{ 
    this->my_Contents += A.my_Contents; 
    return *this; 
} 
+1

這是不正確的。操作員不需要修改*'* this'或'A'。這對'operator + ='更合適,甚至在那裏,return * type *將是一個非const引用。 – WhozCraig

+0

糟糕我的壞處。豎起大拇指。編輯。 – aaa

+1

也許編輯,但它仍然是不正確的。 'operator +'應該返回操作的一個按值結果,保持操作數不變。當你寫'y = 5; x = y + 7;'你不希望'y'突然等於'12'。這個邏輯也不應該在這裏適用。 – WhozCraig