【问题标题】:Incomplete field type c++不完整的字段类型c ++
【发布时间】:2014-03-18 12:02:32
【问题描述】:

我正在编写一个小型 c++ 游戏,但我对 c++ 很陌生,因为通常我是用 java 编写东西。所以我不确定问题出在哪里。

头文件:

#include <string>
class Game;
class SpeedRatio;

class Monster
{
  private:
    ...
    SpeedRatio speed_ratio_; // LINE 36
    ...
public:

    Monster();

    //--------------------------------------------------------------------------
    // Init Constructor
    // @param name the monsters name.
    // @param attack_damage the monsters attack damage.
    // @param life the monsters life.
    // @param attribute the monsters attribute.
    // @param speed_ratio the speed ratio.
    // @param game the game object.
    //
    Monster(std::string name, unsigned int attack_damage, unsigned int life,
            unsigned int attribute, SpeedRatio speed_ratio, Game &game);

}

CPP 文件:

#include "Monster.h"
#include "Game.h"
#include "SpeedRatio.h"

//------------------------------------------------------------------------------
Monster::Monster()
{
}
//------------------------------------------------------------------------------
Monster::Monster(std::string name, unsigned int attack_damage,
                 unsigned int life, unsigned int attribute,
                 SpeedRatio speed_ratio, Game &game) : name_(name),
                 attack_damage_(attack_damage), life_(life),
                 attribute_(attribute), speed_ratio_(speed_ratio), // LINE 39
                 game_(&game)
{

}

SpeedRatio.h

class SpeedRatio
{
  private:
    unsigned int events_;
    unsigned int ticks_;

  public:

    SpeedRatio();

    //--------------------------------------------------------------------------
    // Init Constructor
    // @param events the events.
    // @param ticks the ticks.
    SpeedRatio(unsigned int events, unsigned int ticks);
}

现在我收到 2 条错误消息:

描述 资源路径 位置 类型 字段“speed_ratio_”的类型不完整 Monster.h /ass1 第 36 行 C/C++ 问题
描述 资源路径 位置 类型 “怪物”​​类没有任何名为“speed_ratio_”的字段 Monster.cpp /ass1 第 39 行 C/C++ 问题

T 认为我(希望)我的前向声明是正确的。 我用 cmets 标记了这些行,谢谢您的帮助

【问题讨论】:

标签: c++ header-files


【解决方案1】:

您需要在头文件中完整定义SpeedRatio 类,因为您使用的是完整对象而不是引用或指针。编译器需要知道对象的大小才能生成代码。

前向声明(class SpeedRatio;) 只引入一个类型的名称或声明它但没有定义它,所以编译器说该类型不完整。

修复可能是将相应的包含从 .cpp 移动到 .h,或者改为使用引用或指针(smart_ptr 或 unique_ptr)。

【讨论】:

    【解决方案2】:

    你只声明了类 SpeedRatio

    class SpeedRatio;
    

    但未定义。所以这种类型是不完整的:编译器不知道这种类型的对象的大小。所以编译器无法在 Monster 类的定义中定义数据成员 speed_ratio_。

    class Monster
    {
      private:
        ...
        SpeedRatio speed_ratio_; 
    

    您应该在标题Monster.h 中包含标题SpeedRatio.h

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-25
      相关资源
      最近更新 更多