当类包含在另一个类中时,为什么不倾向于类的工作声明 [英] Why doesn't foward declaration of class work when class is included in another class

查看:115
本文介绍了当类包含在另一个类中时,为什么不倾向于类的工作声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编译

#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指针,但为什么不向前声明。
不是class Sprite;告诉Sprite存在?
我试着#include尽可能多的类在.cpp和避免在.h中的任何代价。
同样的类不包括彼此,所以没有必要使用Sprite *。
我猜我的理解是什么前进声明是错误的或东西,因为我没有看到一个原因,为什么这不工作。

I know that I could forward declare and use pointer for Sprite but why doesn't forward declaration works here. Doesn't "class Sprite;" tells that Sprite exists? I'm trying #include as much classes in .cpp and avoid it in .h at any cost. Also classes are not including each other so there is no need to use Sprite*. I guess my understanding of what forward declaring is is wrong or something because I don't see a reason why this doesn't work.

提前感谢。

推荐答案

假装你是编译器。没有一个完整的声明 Sprite 在您的支配,如何可以确定 Sprite 是否只有一个字节大或十万字节大?

Pretend you're the compiler. Without having a complete declaration of Sprite at your disposal, how is it possible to determine whether the Sprite is only one byte big, or one hundred thousand bytes big?

当你只需要一个指向类的指针时,你不需要知道很多类类,或一些其他小事情);但是当你需要实际使用该类时,只是向前的声明是不够的。这不总是足以知道 Sprite exists;有时需要知道它是多大。没有完整的声明,这是不可能的。

You don't need to know much about the class when you only need a pointer to the class (or a reference to a class, or a few other minor things); but when you need to actually use the class, a mere forward declaration is not sufficient. It's not always enough to know that "Sprite exists"; sometimes it's necessary to know how big it is, too. And without a complete declaration, that's not possible.

这篇关于当类包含在另一个类中时,为什么不倾向于类的工作声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆