为什么类声明顺序仍然与原型相关? [英] Why class declaration ordering still matters with prototyping?

查看:69
本文介绍了为什么类声明顺序仍然与原型相关?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在代码中遇到字段 player类型不完整错误,我的类 game_session包含一个 player,我在相同的头文件中声明了它们,如下所示:

I was struggling with a 'field "player" has incomplete type" error with my code. My class "game_session" contains a single "player" and I declare them both in the same header file as shown below:

#ifndef HEADER_H
#define HEADER_H

#include <iostream>
#include <vector>

using std::vector;

class Player;
class GameSession;

class GameSession{
 private:
  ...
  Player player;
 public:
  GameSession();
  ~GameSession();
  ...
};

class Player {
 public:
  Player( int maxdim );
  ~Player();
  ...
};  

上面的代码无法编译,因为GameSession找不到Player类的声明当我切换两个类时,它起作用,如下所示:

The above code would not compile because the GameSession could not find a declaration for the Player class. It worked when I switched the two classes as shown below:

#ifndef HEADER_H
#define HEADER_H

#include <iostream>
#include <vector>

using std::vector;

class Player {
 public:
  Player( int maxdim );
  ~Player();
  ...
};

class GameSession{
 private:
  ...
  Player player;
 public:
  GameSession();
  ~GameSession();
  ...
};

我不再需要原型。我的问题是,为什么原型制作不能避免由于缺少有序声明而导致的错误?此外,将来如何避免存在许多类和依赖项?

I no longer needed the prototypes. My question is why did the prototyping not prevent the errors from a lack of ordered declaration? Also, how can this be avoided in the future for when there are many classes and dependencies?

Danke

(对于那些想知道的人,我在类实现中使用了一个初始化程序列表来处理Player没有默认构造函数的事实)。

(For those wondering, I used an initializer list in the class implementation to deal with the fact Player does not have a default constructor)

推荐答案

要完全声明 GameSession ,编译器需要弄清楚其所有成员的大小。因此,由于有一个 Player 成员,因此需要 Player 的完整声明。

To fully declare GameSession the compiler needs to figure out the size of all of its members. So since there is a Player member, it needs the full declaration of Player.

如果该 player 成员是指针或引用,则编译器不需要完全声明 Player 是因为编译器已经知道指针或引用的大小,而不管指向或引用的是哪种类型的类。

If that player member was instead a pointer or reference, then the compiler wouldn't need to full declaration of Player because the compiler already knows the size of a pointer or reference regardless of what type of class is points or refers to.

据我所知在使用作为类实例的成员时,没有任何神奇的方法可以解决具有完整声明的要求。因此,您必须选择自己喜欢的技术和相应要求。

As far as I know there aren't any magic ways to work around the requirement of having the full declaration when using a member that's an instance of a class. So you have to choose which technique and corresponding requirements you prefer.

这篇关于为什么类声明顺序仍然与原型相关?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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