[英]How to overload the increment operators in C++ for an Object with 2 variables?
所以我一直遇到運算符重載的問題。 所以我有一個程序,它有一個名為Weight的對象,它有 2 個屬性,磅和盎司。 我想出了所有其他運算符,但增量運算符一直給我帶來麻煩。 我試圖這樣做,但由於某種原因,它不想工作。
以下是頭文件中的聲明(包括 2 個變量):
void operator++();
void operator--();
private:
int pounds;
int ounces;
和成員函數:
void Weight::operator++() {
pounds + 1;
ounces + 15;
}
void Weight::operator--() {
pounds - 1;
ounces - 15;
}
什么都有幫助!
發布的代碼有兩個問題。
不清楚當您增加或減少一個Weight
對象時會發生這種情況。 如果它的價值上升/下降一盎司或一磅。
表達式pounds + 1
、 ounces + 15
等不會改變對象中的任何內容。 他們計算一個值,結果被丟棄。
假設 inrement 運算符將值更改一盎司,您必須使用:
void Weight::operator++() {
ounces++;
// If ounces becomes 16, we have to increment pounds by one and set ounces to zero.
if ( ounces == 16 )
{
pounds++;
ounces = 0;
}
// That can also be achieved by using.
// pounds += (ounces / 16);
// ounces = (ounces % 16);
}
此外,重載++
運算符的規范做法是返回對對象的引用。 因此,您應該使用:
Weight& Weight::operator++() {
ounces++;
// If ounces becomes 16, we have to increment pounds by one and set ounces to zero.
if ( ounces == 16 )
{
pounds++;
ounces = 0;
}
// That can also be achieved by using.
// pounds += (ounces / 16);
// ounces = (ounces % 16);
return *this;
}
您必須以類似的方式更新operator--
功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.