2016-11-20 57 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 ++? –