获取错误“......没有名称类型”的东西

Getting Error "...does not have a name type" for Something that Does

我目前正在这里开发一个基于文本的小型角色扮演游戏,我 运行 遇到了一个问题。我正在制作一个包含游戏中所有武器的 class(也许有更好的方法来制作武器列表,但这是我选择的路线)。我目前的代码是:

#ifndef LISTOFWEAPONS_H
#define LISTOFWEAPONS_H

#include "Weapon.h"

#include <iostream>

using namespace std;

class ListOfWeapons
{
public:
    ListOfWeapons();

    //BASIC (starter) WEAPONS
    //----------------------------------------
    Weapon iron_axe(common, axe, "Iron Axe", 1);
    Weapon iron_sword(common, sword, "Iron Sword", 1);
    Weapon iron_mace(common, mace, "Iron Mace", 1);
    Weapon iron_spear(common, spear, "Iron Spear", 1);
    Weapon iron_staff(common, staff, "Iron Staff", 1);
    Weapon iron_dagger(common, dagger, "Iron Dagger", 1);
    Weapon wood_bow(common, bow, "Wood Bow", 1);
    Weapon wood_crossbow(common, crossbow, "Wood Crossbow", 1);
    Weapon iron_throwing_knife(common, thrown, "Iron Throwing Knife", 1);
    Weapon blunderbuss(common, gun, "Blunderbuss", 1);
    //----------------------------------------

protected:

private:
};

#endif // LISTOFWEAPONS_H

现在,当我编译这段代码时,出现错误 error: 'Weapon' does not name a type。 Weapon 是它自己的 class,编译和工作完全正常;所以我的问题是,我到底做错了什么?感谢您的宝贵时间!

您定义了一个 class 名称的武器列表,但没有定义一个 class 名称的武器

试试这个:

class ListOfWeapons
{
public:
    ListOfWeapons()
        // This is the constructor's "initializer list".
        : iron_axe(common, axe, "Iron Axe", 1),
          iron_sword(common, sword, "Iron Sword", 1)
          // ... 
    {

    }


    //BASIC (starter) WEAPONS
    //----------------------------------------
    Weapon iron_axe;
    Weapon iron_sword;
    // ...
    //----------------------------------------
};

重点是你的 Weapon 成员变量在错误的地方初始化。

当你有需要在构造过程中初始化的成员变量时,初始化列表总是最好的地方。

考虑一个更简单的例子:

class Person {
public:
  Person() : age_(0) {}
  Person(const std::string& name, int age) : name_(name), age_(age) {}

private:
  std::string name_;
  int age_;
};

Class Person有两个成员变量和两个构造函数。第一个构造函数称为 "default" 因为它不带任何参数,而第二个构造函数是一个普通的构造函数,您可以在其中为新的 Person 对象指定姓名和年龄。

Person person1;  // 1st constructor
Person person2("Adam", 26);  // 2nd constructor

您可以在声明它们的地方初始化某些类型的成员变量。但这仅适用于原语(int、bool 等)。在您的示例中,Weapon 不是原始类型,因此您不能在声明它们时进行初始化。