1
我想提供一個對象的一次性配置。C++ 11類的靜態結構編譯,爲什麼不鏈接?
此代碼:
class Foo
{
public:
static struct Bar {
bool a = true;
int b = 69;
} bar;
};
int main(int argc, char **argv)
{
Foo::bar.a = false;
}
編譯就好:
$ g++ -c -std=gnu++11 main.cpp
但鏈接器抱怨缺少符號:
$ g++ main.o
Undefined symbols for architecture x86_64:
"Foo::bar", referenced from:
_main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
爲什麼不這項工作?
and
什麼是實現同樣目標的更好方法?
啊!我認爲支撐或平等初始化器會這樣做。我會盡快接受...你打賭接受計時器。 – helpwithhaskell
@helpwithhaskell你只能初始化內部類的數據成員,而不能初始化靜態類成員'bar'的數據成員。因此,任何代碼如:'Foo :: Bar b;'都會將'b'的數據成員初始化爲您提供的值,這將是變量'b'的定義,就像上面的'Foo :: Bar Foo :: bar'是Foo(靜態成員)變量bar的定義。 – rubenvb