2016-11-20 58 views
-1

不會編譯:在C++中,我們如何在計算類成員變量大小的類中定義靜態常量?

class A 
{ 
    int m_x; 
public: 
    static const int SIZE = sizeof(m_x); 
}; 

我想有A::SIZE等於成員變量m_x的大小。我們該怎麼做?

我使用Visual Studio 2015以下是錯誤:

1>c:\users\markk\documents\visual studio 2015\projects\b\b.cpp(10): error C2327: 'A::m_x': is not a type name, static, or enumerator 
1>c:\users\markk\documents\visual studio 2015\projects\b\b.cpp(10): error C2065: 'm_x': undeclared identifier 

編譯命令行:

/Yu"stdafx.h" /GS /W3 /Zc:wchar_t /ZI /Gm /Od /sdl /Fd"x64\Debug\vc140.pdb" /Zc:inline /fp:precise /D "_DEBUG" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /errorReport:prompt /WX- /Zc:forScope /RTC1 /Gd /MDd /Fa"x64\Debug\" /EHsc /nologo /Fo"x64\Debug\" /Fp"x64\Debug\b.pch" 

編輯1

感謝Stargateur。稍微改變它也適用於VS2015:

class A 
{ 
    int m_x; 
public: 
    static const int SIZE; 
}; 

const int A::SIZE = sizeof(A::m_x); 

結果比我想象的要容易。

+1

無法重現:http://melpon.org/wandbox/permlink/ixMr4kRkJft1c9PB – krzaq

+0

作品[精這裏](http://coliru.stacked-crooked.com/a/211cd37638375b76)。你在問什麼?你不會告訴我們你在課堂宣言後錯過了分號,對嗎? –

+1

在c + + 03它不起作用,但它會更清楚的實際的錯誤信息... 14K代表你應該知道這一點。 –

回答

1

剛看完doc

foo.h中

#include <cstddef> 

class Foo 
{ 
private: 
    int bar; 
public: 
    static size_t const foo; 
}; 

Foo.cpp中

#include "foo.h" 

size_t const Foo::foo = sizeof(Foo::bar); 
+0

我不是要求'sizeof(int)'。我要求'sizeof(m_x)'。這是不一樣的。 – mark

+0

@mark爲你的案例編輯 – Stargateur

+0

@Stargateur你測試過VS 2015還是GNU g ++? –