2015-07-10 58 views
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

什麼是實現同樣目標的更好方法?

回答

6

變量只宣佈類的定義裏面,所以你需要這個靜態變量的(單)的定義,作爲任何其他靜態變量:

Foo::Bar Foo::bar; 

Live demo。請記住,整個二進制文件中只能有一個定義(無論是庫還是可執行文件),因此此定義不能位於可從多個翻譯單元(,即源文件)中包含的標題中。

+0

啊!我認爲支撐或平等初始化器會這樣做。我會盡快接受...你打賭接受計時器。 – helpwithhaskell

+0

@helpwithhaskell你只能初始化內部類的數據成員,而不能初始化靜態類成員'bar'的數據成員。因此,任何代碼如:'Foo :: Bar b;'都會將'b'的數據成員初始化爲您提供的值,這將是變量'b'的定義,就像上面的'Foo :: Bar Foo :: bar'是Foo(靜態成員)變量bar的定義。 – rubenvb

相關問題