2012-04-16 31 views
0

在我們的一本教科書中,建議我們應該在C++中使用接口作爲優秀的設計實踐。他們舉例如下;這個方法名前的const是什麼意思?

class IAnimation 
{ 
    public: 
     virtual void VAdvance(const int deltaMilisec) = 0; 
     virtual bool const VAtEnd() const = 0; 
     virtual int const VGetPostition() const = 0; 
}; 

我沒有得到的含義:

virtual bool const VAtEnd() const = 0; 
virtual int const VGetPostition() const = 0; 

我知道const的是()之後使用,使他們從const的情況下可調用。但是在VAtEnd和VGetPosition(方法名稱)之前的const是什麼意思?

謝謝。

+0

它看起來像代碼作者試圖使其難以被理解的代碼! – 2012-04-16 16:26:45

+0

const綁定到左邊(除非它在左邊然後在綁定右邊)。 – 2012-04-16 16:35:55

回答

7

這意味着返回類型爲常量,這是一樣的:

virtual const bool VAtEnd() const = 0; 
virtual const int VGetPostition() const = 0; 

它沒有任何實際意義,雖然,作爲返回值是無論如何都會被複制。

如果你會雖然返回一個對象:

struct A 
{ 
    void goo() {} 
}; 

const A foo() {return A();} 



int main() 
{ 
    A x = foo(); 
    x.goo();  //ok 
    foo().goo(); //error 
} 
+0

謝謝@Luchian Grigore。我必須修改我的C++知識。順便說一下const布爾更直觀。是的,因爲我是新來的這裏SOF要求我等待9分鐘,然後纔可以將您的帖子標記爲答案:(。 – Mahesha999 2012-04-16 16:30:37

+0

這是爲了防止怪異類似於:'VGetPostition()= 4'或任何賦予函數真的。不知道爲什麼你想這樣做 – Dennis 2012-04-16 16:37:06

+1

@ Mahesha999:哪一個更具可讀性,需要討論,我更喜歡'const'在右邊,因爲它更加一致,因此花費更少的思考努力,考慮'typedef int * intp;',現在'const int *'和'const intp'是不同的類型,但是'int * const'和'intp const'是一樣的(也就是說,如果你願意,你可以在心理上用類型替換typedef的地方在右側寫上'const',但如果'const'在左側,則不能這樣做' – 2012-04-16 16:49:30