2012-05-31 80 views
7

我的Test類有conststatic子類型的成員。我通常如下定義這個conststatic成員。如何定義靜態const成員?

class Test 
{ 
public: 
    class Dummy {}; 

private: 
    static Dummy const dummy; 

}; 

Test::Dummy const Test::dummy;    // ERROR HERE 

int main() 
{ 
    return 0; 
} 

使用gcc-4.6編譯此源代碼時,它不會發生錯誤並且編譯正確。

使用gcc-4.4編譯這個相同的源代碼時,它會給出以下錯誤: error: uninitialized const ‘Test::dummy’ 在標記的行上。

  • 是否有另一種方法來定義這個靜態const成員變量?
  • 這是gcc-4.4的限制嗎?
  • 是否有解決方法?
+2

'測試假人::常量的Test ::虛擬=測試::假人( );' – dasblinkenlight

回答

6

說:

Test::Dummy const Test::dummy = { }; 
+0

雖然不會用gcc 4.4,還是會呢? – bstamour

+1

只要'Test :: Dummy'是聚集的(C++ 03),或者始終在C++ 11中,就應該工作。 –

+0

啊對,虛擬是一種POD類型。 – bstamour

1

,你還可以添加一個默認的構造函數來class Dummy

class Dummy { public: Dummy(){} }; 

在第4行

編輯: 看來,GCC 4.4沒有生成Dummy類的默認ctor。因此上面直接克服了這個編譯器的bug。

+1

不需要,'Dummy'有一個編譯器合成的默認構造函數。 – juanchopanza

+0

@juanchopanza好,在gcc 4.3.2下,上面修正了這個問題*沒有*其他任何修改的原代碼 – Walter

+0

暗示編譯器bug ...... – juanchopanza

0

使用GCC 4.4,使用

Test::Dummy const Test::dummy = Test::Dummy; 

隨着編譯器支持C++ 11,你可以使用統一初始化語法:

Test::Dummy const Test::dummy = { }; 

但我不認爲這由GCC 4.4的支持。

+0

你的第一個解決方案不適用於gcc 4.3.2,但第二個解決方案(a Kerrek SB)可以。 – Walter

+0

第一個應該使用'Test :: Dummy()'而不是'Test :: Dummy'。對於第二種,統一的初始化語法應該是'=',即'Test :: Dummy const Test :: dummy {};' –

2

http://gcc.gnu.org/wiki/VerboseDiagnostics#uninitialized_const(可提供相關參考標準),也是GCC 4.6 release notes這不能不

In 4.6.0 and 4.6.1 G++ no longer allows objects of const-qualified type to be default initialized unless the type has a user-declared default constructor. In 4.6.2 G++ implements the proposed resolution of DR 253 , so default initialization is allowed if it initializes all subobjects. Code that fails to compile can be fixed by providing an initializer e.g.

struct A { A(); }; 
struct B : A { int i; }; 
const B b = B(); 

Use -fpermissive to allow the old, non-conforming behaviour.

相關問題