[英]Why doesn't foward declaration of class work when class is included in another class
这样编译
#include "Sprite.h"
class GameObject
{
public:
int x, y, w, h;
Sprite sprite;
public:
GameObject();
GameObject(int _x, int _y, int _w, int _h);
virtual ~GameObject();
};
这不是
class Sprite;
class GameObject
{
public:
int x, y, w, h;
Sprite sprite;
public:
GameObject();
GameObject(int _x, int _y, int _w, int _h);
virtual ~GameObject();
};
我知道我可以向前声明并使用Sprite的指针,但是为什么不向前声明在这里起作用。 不对Sprite进行分类; 告诉雪碧存在吗? 我正在尝试#include .cpp中的所有类,并不惜一切代价避免在.h中使用它。 另外,类之间不包括彼此,因此不需要使用Sprite *。 我想我对前向声明的理解是错误的或什么原因,因为我看不出为什么这行不通。
提前致谢。
假装您是编译器。 在没有完整的Sprite
声明Sprite
下,如何确定Sprite
是仅一个字节还是十万个字节呢?
当您只需要指向该类的指针(或对一个类的引用,或其他一些小事)时,您不需要对类有太多了解; 但是当您需要实际使用该类时,仅向前声明是不够的。 仅仅知道“ Sprite
存在”并不总是足够的。 有时也有必要知道它有多大。 没有完整的声明,这是不可能的。
如果类型出现在从属类声明中,则前向声明仅适用于引用或指针。
class Sprite;
class GameObject
{
public:
int x, y, w, h;
Sprite* sprite; // <<<<
// or Sprite& sprite;
public:
GameObject();
GameObject(int _x, int _y, int _w, int _h);
virtual ~GameObject();
};
注意将Sprite.h
文件包含在您的实现中,并在理想的情况下在构造函数实现中初始化该成员(严格按引用要求)。
Sprite
不能是不完整的类型 ,因为必须将其大小和布局称为GameObject
类的非静态成员。
(注意第三个)
以下任何上下文均要求类
T
是完整的:definition or function call to a function with return type T or argument type T; definition of an object of type T; declaration of a non-static class data member of type T; new-expression for an object of type T or an array whose element type is T; lvalue-to-rvalue conversion applied to a glvalue of type T; an implicit or explicit conversion to type T; a standard conversion, dynamic_cast, or static_cast to type T* or T&, except when converting from the null pointer constant or from a pointer to void; class member access operator applied to an expression of type T; typeid, sizeof, or alignof operator applied to type T; arithmetic operator applied to a pointer to T; definition of a class with base class T; assignment to an lvalue of type T; a catch-clause for an exception of type T, T&, or T*.
另一方面,如果将其声明为指针或引用,则可以使用不完整的类型,并允许进行正向声明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.