类不存在默认构造函数,但传递了非默认构造函数



My Thing 类派生自具有以下构造函数的 Entity 类

    Entity::Entity(string sNames, double xcord, double ycord)
    :m_sName(sNames), m_dX(xcord),m_dY(ycord){}

事物的构造函数是

    Thing::Thing(string sName, double xcord, double ycord):
    Entity(sName, xcord, ycord),
    m_iHealth(100),m_Weapon(Weapon("Fists", false, 10.0, 5, 1.0, xcord, ycord)){}

问题是我在我的 Thing 构造函数上收到错误"没有合适的默认构造函数可用"。 我指定使用我的实体构造函数而不是默认值的问题是什么。 为了使问题对我来说更加混乱,我从实体中获得了另一个有效的类

    Weapon::Weapon(string sName, bool iMagical, double dRange, int iDamage,double
    dRadius, double dSpawnX, double dSpawnY):
    Entity(sName, dSpawnX, dSpawnY), m_bMagical(iMagical), m_dRange(dRange), m_iDamage(iDamage),
    m_dRadius(dRadius)
{
}

它运行没有错误,但它似乎与我的 Thing 构造函数完全相同,具有更多变量。 我确定我错过了一些小东西,但我已经难倒了一段时间。

你是对的,有一些剩余的代码没有被注释掉。 构造函数中出现成员变量减速的错误似乎很奇怪,但无论如何都要感谢。 帽子带给我的总是简单的东西。

也许你的Thing实际上没有默认的构造函数,需要一个。像这样的程序可能会产生您看到的错误。

#include <string>
using std::string;
struct Entity {
  std::string m_sName;
  double m_dX, m_dY;
  Entity(std::string, double, double);
};
struct Weapon : Entity {
  bool m_bMagical;
  double m_dRange;
  int m_iDamage;
  double m_dRadius;
  Weapon(std::string, bool, double, int, double, double, double);
};
struct Thing : Entity {
  int m_iHealth;
  Weapon m_Weapon;
  Thing(std::string, double, double);
};

// OP's code starts here
Entity::Entity(string sNames, double xcord, double ycord)
    :m_sName(sNames), m_dX(xcord),m_dY(ycord){}
Thing::Thing(string sName, double xcord, double ycord):
    Entity(sName, xcord, ycord),
    m_iHealth(100),m_Weapon(Weapon("Fists", false, 10.0, 5, 1.0, xcord, ycord)){}
Weapon::Weapon(string sName, bool iMagical, double dRange, int iDamage,double
    dRadius, double dSpawnX, double dSpawnY):
    Entity(sName, dSpawnX, dSpawnY), m_bMagical(iMagical), m_dRange(dRange), m_iDamage(iDamage),
    m_dRadius(dRadius)
{
}
// OP's code ends here
int main () {
  Thing th;
}

在 g++ 下,精确的错误是:

th.cc: In function ‘int main()’:
th.cc:40: error: no matching function for call to ‘Thing::Thing()’
th.cc:27: note: candidates are: Thing::Thing(std::string, double, double)
th.cc:16: note:                 Thing::Thing(const Thing&)

假设Thing::m_Weapon被声明为Weapon而不是Weapon*Weapon&或等效,那么你需要改变这一点:

m_Weapon(Weapon("Fists", false, 10.0, 5, 1.0, xcord, ycord))

对此

m_Weapon("Fists", false, 10.0, 5, 1.0, xcord, ycord)

您正在构造一个临时Weapon,然后尝试从该温度构造m_Weapon。 据推测,Weapon没有将Weapon作为输入的复制构造函数。