[問題] static const 的問題
開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
linux & windows 7
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
無
問題(Question):
大家好
我在 class 裡面定義了一些常數
// foo.h
class Foo {
public:
static const int FOO = 1;
static const int BAR = -1;
};
但是發現一件奇怪的事情,在另一個檔案中
// main.cpp
#include "foo.h"
int main() {
int a = Foo::FOO; // ok
int b = (a > 0) ? Foo::FOO : Foo::BAR; // error: undefined reference
// to 'Foo::FOO' and 'Foo::BAR'
switch (b) { // ok
case Foo::FOO:
case Foo::BAR:
default:
break;
}
return 0;
}
build 指令是 'g++ main.cpp'
g++ 版本 4.4.7,vc2012 沒有這個問題
這樣寫不是宣告同時定義了嗎??怎麼會是 undefined reference
而且拿掉 int b 那行後即可順利 build 並執行
後來實在想不透,因此遵循古法,把定義跟宣告分開寫,改成
// foo.h
class Foo {
public:
static const int FOO;
static const int BAR;
};
// foo.cpp
#include "foo.h"
const int Foo::FOO = 1;
const int Foo::FOO = -1;
build 指令為 'g++ main.cpp foo.cpp'
但這次問題變成
// main.cpp
#include "foo.h"
int main() {
int a = Foo::FOO; // ok
int b = (a > 0) ? Foo::FOO : Foo::BAR; // ok
switch (b) {
case Foo::FOO: // error: 'Foo::FOO' and 'Foo::BAR'
case Foo::BAR: // cannot appear int a constant-expression
default:
break;
}
return 0;
}
vc2012 同樣地方也出現 error: case 運算式不是常數
請問這是什麼情況??
static const 到底該如何宣告定義才是最正確的呢??
謝謝大家
餵入的資料(Input):
無
預期的正確結果(Expected Output):
無
錯誤結果(Wrong Output):
無
程式碼(Code):(請善用置底文網頁, 記得排版)
請看上面
補充說明(Supplement):
無
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 118.163.58.205
→
11/15 11:17, , 1F
11/15 11:17, 1F
→
11/15 11:55, , 2F
11/15 11:55, 2F
→
11/15 11:55, , 3F
11/15 11:55, 3F
→
11/15 11:55, , 4F
11/15 11:55, 4F
推
11/15 12:50, , 5F
11/15 12:50, 5F
→
11/15 13:18, , 6F
11/15 13:18, 6F
→
11/15 15:14, , 7F
11/15 15:14, 7F
→
11/15 15:15, , 8F
11/15 15:15, 8F
推
11/15 15:21, , 9F
11/15 15:21, 9F
→
11/15 17:21, , 10F
11/15 17:21, 10F
→
11/15 19:27, , 11F
11/15 19:27, 11F
→
11/16 02:20, , 12F
11/16 02:20, 12F
→
11/16 20:30, , 13F
11/16 20:30, 13F
→
11/18 00:34, , 14F
11/18 00:34, 14F
→
11/18 00:35, , 15F
11/18 00:35, 15F
→
11/18 00:35, , 16F
11/18 00:35, 16F
→
11/18 23:51, , 17F
11/18 23:51, 17F
→
11/19 00:12, , 18F
11/19 00:12, 18F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章