2014-01-11 64 views
0

在這個函數中const函數:C++參考

(計數器是其中的函數operator ++聲明類)

const Counter& operator++(); 

什麼意思我函數常量?我不太瞭解const關鍵字與指針或引用的結合!

+0

它返回「Counter」類型的常量引用。只有在函數出現在聲明的末尾時,'const'才適用於該函數。如果它出現在聲明的開頭,它就適用於返回的類型。 –

+0

但const使某些東西不能改變,現在我不能改變什麼? –

+1

[Const Correctness](http://www.parashift.com/c++-faq/const-correctness.html)。這將幫助你理解:) – demonking

回答

0

這意味着你可能不會使用這個引用來改變它所反對的對象。例如,如果你有型計數器

Counter obj1, obj2; 

的兩個對象便可不寫

++obj1 = obj2; 

因爲由於限定符const的對象由操作者返回的參考refered至++是不可變的。

如果你想刪除的操作符聲明const限定符那麼這種說法

++obj1 = obj2; 

將是有效的。

實際上,聲明preincrement運算符返回const引用並不是一個好主意。通常它宣稱沒有const限定符

Counter& opperator++(); 

在這種情況下,它的行爲方式與前遞增運算符++算術tyoes相同。例如,此代碼有效

int x = 1;

++ x = 2;

並且結果是x = 2;

1

這是一個運算符重載,但聲明語法與函數類似。你的聲明可以分爲3個部分:

  • 返回類型:const Counter&
  • 函數名稱:operator++
  • 和參數類型:()(無參數)

所以const Counter &告訴您該函數將返回一個對Counter對象的常量引用。一個常量引用使得對象不能被修改。

例如:

Counter c1; 
++(++c1); // invalid 

這裏(++c1)返回const referenceCounter對象。該引用增加,但是無效,因爲該引用不能被修改(它是常量)。

+0

您將preincrement運算符與postincrement運算符混淆後顯示錶達式計數器c1; (c1 ++)++; //無效 –

+0

@VladfromMoscow ty,我的壞 – bolov

0

到這裏說明我的意見的例子:

class xy 
{ 
private: 
    int i; // const int i when object of xy is const 
    int *ptr; // int *const ptr when object of xy is const 

public: 
    xy() : i(0), ptr(&i) { } // const i initialized to 0, only possible in constructor 
          // ptr pointing to i 

    void set (int s) { i=s; } // changes i, not possible to define this member function 
           // as const like read() 

    int read() const { return i; } // reads i 

    void ptr_set (int s) const { *ptr = s; } 
}; 

int main() 
{ 
    const xy obj; 
    int read = obj.read(); // read() is allowed for const objects 

    obj.set(10); // not allowed! you could not define set() as const (like read()): 
       // there would be a compiler error, because this member function 
       // would try to change const i 

    obj.ptr_set(10); // allowed, would change i through pointer 

    return 0; 
} 

順便說一句,任何人都可以解釋爲什麼像obj.ptr_set(10)畢竟是可能的const正確性的意義嗎?