关于 C++ 中 sizeof(class) 使用引发的错误
当我用 C++ 编译项目时,MSVC 抛出以下错误:
错误#94:数组的大小必须大于零
在执行 sizeof 时,在以下行中抛出错误:
if (sizeof (MyNamespace::MyClass) == 60)
MyClass 的定义如下:
class MyClass: public ParentClass
{
public:
MyClass( void *pCreate, int a, int b, bool c) :
ParentClass( pCreate, a, b, c ) {}
virtual inline void myFunc ( )
{
//something
}
private:
virtual ~MyClass(){};
/**
* Copy assignment. Intentionally made private and not implemented to prohibit usage (noncopyable stereotype)
*/
MyClass& operator=(const MyClass&);
};
任何人都可以告诉我可能出了什么问题吗?即使 sizeof 返回零大小,为什么会出现编译器错误?
When I compile my project in C++, the following error is thrown by MSVC :
error #94: the size of an array must be greater than zero
The error is thrown in the following line on doing sizeof :
if (sizeof (MyNamespace::MyClass) == 60)
MyClass is defined thus :
class MyClass: public ParentClass
{
public:
MyClass( void *pCreate, int a, int b, bool c) :
ParentClass( pCreate, a, b, c ) {}
virtual inline void myFunc ( )
{
//something
}
private:
virtual ~MyClass(){};
/**
* Copy assignment. Intentionally made private and not implemented to prohibit usage (noncopyable stereotype)
*/
MyClass& operator=(const MyClass&);
};
Can anyone tell me what might be wrong? Even if sizeof returns zero size, why is it a compiler error?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您获取当时仅声明的类的
sizeof
时,就会导致此错误。例如class MyClass; const size_t error = sizeof(MyClass);
。请注意,稍后是否完全定义该类并不重要:定义必须位于
sizeof
之前。This error is caused when you take the
sizeof
of a class that's only declared at that point. E.g.class MyClass; const size_t error = sizeof(MyClass);
.Note that it doesn't matter whether the class is fully defined later: the definition must precede the
sizeof
.此错误很可能是由前向声明引起的。在使用 sizeof 的行中,编译器需要知道类 MyClass 的定义,即您必须 #included 其头文件
This error is most likely caused by a forward declaration. At the line where you use sizeof, the compiler needs to know the definition of your class MyClass, that is you must have #included the header file for it