[英]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.