C++FAQ

Tuesday, February 07, 2006

 

為什麼我應該使用++i,而不要使用i++?

Q: 有人和我說如果我要對一個變數做增加(increment)的動作 ,我應該使用 ++x 而不是使用 x++,這是真的嗎?

A: 如果你要做的事就只是增加 (沒有要把這個變數給(assign)別人),那麼這是個好習慣,特別是你在一個class上使用increment operator時。

// Prefix operators are preferred in cases in the following common cases:

for (;checkstate(x);++x) dosomething(x);

++x;
標準的資料型態其實是不會有效能上的差異,但是對於 class 的確是有的。原因是(大多數的實作上),postfix operator會對原本的變數做一個暫時的複製,而回傳值是以 by value 的方式回傳,不是 by reference,下面的這個例子可以說明一切:

class MyClass
{
public:
MyClass& operator++() //Prefix increment operator (++x)
{
//Perform increment operation
return *this;
}

MyClass operator++(int) //Postfix increment operator (x++)
{
MyClass temp = *this;
//Perform increment operation
return temp;
}
};

Comments: Post a Comment



<< Home

Archives

January 2006   February 2006  

This page is powered by Blogger. Isn't yours?