作者adrianshum (Alien)
看板Programming
標題Re: static variable and const method in C++
時間Sat Apr 12 23:33:07 2008
※ 引述《previewslave (蝦蝦蝦蝦 來玩圍棋吧)》之銘言:
: 嗨,陳君,在下是大師。
:
: 在類別內:(C++)
: class CA()
: {
: static int x;
: …
: void fA() { … }
: …
: };
: int CA::x = 0; // 使用範疇算子 :: 來設定。別忘了要加上型態
錯。
最重點是要放在 source file 裡作 initialization.
照你這樣寫又放在 header 還是會 error
:
: 其他:在類別的靜態函數內,用法如同在函式內。
:
: ※ 引述《sorryChen (陳揚和)》之銘言:
: : 寫了那麼多年C++很汗顏 這個基本的概念沒搞懂
: : 以前只用 static const variable,直接在.h class define就assign了
: : 或用 static function
: : 就是沒用到成員變數 不需要new instance就可以call的函數)
: : 但一直沒搞懂 首先 如果定義static (not const) variable,要在哪裡initialize
: : 外面或是成員函式嗎?
: : 還有 const function
: : (可參看 http://en.wikipedia.org/wiki/Static_variable)
: : 是說 如他那樣定義 是說可以改變const variable嗎
: : 而且在他C++的例子中count並非constant..只是static
: : 為什麼需要const function去回傳他呢
: : 希望有大師可以回答
:
: --
: ※ 發信站: 批踢踢實業坊(ptt.cc)
: ◆ From: 211.76.58.205
: 推 sorryChen:大師 好像還是有link error LK2005 128.125.87.33 04/12 16:17
: → sorryChen:大師,為何wiki的例子中Count()要加const 128.125.87.33 04/12 16:18
: → previewslave:問題一,解:請貼完整程式碼。 211.76.58.205 04/12 21:07
: → previewslave:問題二,解:此乃保證不更動物件變數 211.76.58.205 04/12 21:08
: → previewslave: 之宣告。 211.76.58.205 04/12 21:09
補充一點。
加上 const 作此保證的引申效用則是可以 invoke 一個 const object instance
的該 method.
class Foo {
public:
void constBar() const;
void nonConstBar();
}
void main() {
const Foo constFoo;
constFoo.constBar(); // 行
constFoo.nonConstBar(); // 不行
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 219.78.81.71
推 previewslave:唉呀,果然是大師。 211.76.58.205 04/13 00:18
※ 編輯: adrianshum 來自: 219.78.81.71 (04/13 01:45)
推 sorryChen:大師..其實不懂為何.nonConstBar不行 128.125.87.33 04/13 03:57