[英]Overload ++ operator
我試圖在第一次處理運算符重載,並且我編寫了這個代碼來重載++運算符以將類變量i
和x
遞增一個..它完成了工作,但編譯器顯示了這些警告:
警告1警告C4620:找不到類型'tclass'的'operator ++'的后綴形式,使用前綴形式c:\\ users \\ ahmed \\ desktop \\ cppq \\ cppq \\ cppq.cpp 25
警告2警告C4620:找不到類型'tclass'的'operator ++'的后綴形式,使用前綴形式c:\\ users \\ ahmed \\ desktop \\ cppq \\ cppq \\ cppq.cpp 26
這是我的代碼:
class tclass{
public:
int i,x;
tclass(int dd,int d){
i=dd;
x=d;
}
tclass operator++(){
i++;
x++;
return *this;
}
};
int main() {
tclass rr(3,3);
rr++;
rr++;
cout<<rr.x<<" "<<rr.i<<endl;
system("pause");
return 0;
}
這個語法:
tclass operator++()
用於前綴++
(實際上通常寫為tclass &operator++()
)。 要區分后綴增量,請添加一個未使用的int
參數:
tclass operator++(int)
另外,請注意前綴增量更好地返回tclass &
因為結果可以在: (++rr).x
。
再次注意,后綴增量如下所示:
tclass operator++(int)
{
tclass temp = *this;
++*this; // calls prefix operator ++
// or alternatively ::operator++(); it ++*this weirds you out!!
return temp;
}
有兩個 ++ operator
。 你定義了一個並使用了另一個。
tclass& operator++(); //prototype for ++r;
tclass operator++(int); //prototype for r++;
后增量和前增量有單獨的重載。 postincrement版本的簽名是operator++(int)
,而preincrement的簽名是operator++()
。
你已經定義了operator++()
,所以你只定義了preincrement。 但是,您在類的實例上使用postincrement,因此編譯器會告訴您它將使用preincrement函數的調用,因為沒有定義postincrement。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.