[an error occurred while processing this directive]
[an error occurred while processing this directive]
enum {MAX = 100};
これで
#define MAX 100と同じような効果が得られます。なお、enumの実体はintです。
const int MAX = 100;と書くだけ。
class A{
const int MAX = 100;
};
はこんなコンパイルエラーになる。
error: ISO C++ forbids initialization of member `MAX' error: making `MAX' staticではどうするか…というと、一つの方法はコンストラクタで初期化する。const変数は代入はできないけど、初期化の操作は代入ではないから可能です。
class A{
const int MAX;
A() : MAX(100){}
};
もしこのconst変数がインスタンスによらず一定 (つまり定数として利用する)のであれば、まずstaticを付ける。これでMAXにはインスタンスごとに別のメモリが割り当てられるのではなく、ただ一つのメモリが共用されるようになる。
class A{
const static int MAX;
/* もっと色々定義を書く */
};
const int A::MAX = 100;
ちょうどクラス内のメンバ関数(メソッド)定義のように書きます。ヘッダファイルではなくて実体のファイル(.cpp)に書きましょう。
class A{
const static int fib[5];
/* もっと色々定義を書く */
};
const int A::fib = {1,1,2,3,5};
class Msg {
public:
typedef enum {
request,
response
} kind;
static char *label(kind k){
switch(k){
case request : return "request";
case response : return "response";
}
assert(0);
return NULL;
}
};
で、こんな風に使う。
Msg::kind mk = Msg::request; std::cout << "mk = " << Msg::label(mk) << std::endl;