类不存在默认构造函数,但传递了非默认构造函数
No default constructor exists for class but non default passed
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
作为输入的复制构造函数。
相关文章:
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 初始化具有非默认构造函数的std::数组项的更好方法
- 具有默认模板类型的默认构造函数的类型推导
- 如何使用非默认构造函数实例化模板化类
- 为什么不调用移动构造函数?(默认情况下只有构造器,没有别的)
- 有没有一种代码密度较低的方法来使用非默认构造函数初始化数组?
- 声明没有默认构造函数的字段
- 基类中的默认析构函数禁用子类中的移动构造函数(如果有成员)
- 没有默认构造函数作为模板参数的自定义比较器
- C++17 没有默认构造函数的地图放置(私有默认构造函数)
- 使用移动调用对等构造函数unique_ptr默认构造函数
- C++复制构造函数和默认构造函数
- 将向量从 N1 缩小到 N2 项,而不触发默认构造函数并仅使用 move 语义
- 构造函数默认公共和私有变量
- 类模板构造函数默认参数
- 构造函数默认参数
- C++模板构造函数默认参数
- 在c++中设置构造函数默认值
- c++构造函数默认参数
- C++构造函数默认值头文件