c++ - 为什么不能在派生类初始化时编译代码?

标签 c++

学习C++并在创建武器距离时出现错误“没有匹配的函数来调用'Weapon::Weapon(int,const char [4],int,int)''”

Weapon MyWeapon(1,"test",4,1);

错误在哪里?

item.h
#ifndef ITEM_H
#define ITEM_H
#include <string>
#include <iostream>

using namespace std;
class Item
{
public:
  string name;
  int weight;
  int value;
  Item(string n, int w, int v);

};
#endif

item.cpp
#include <iostream>
#include <string>
#include <vector>
#include "item.h"
using namespace std;
Item::Item(string name, int weight, int value)
{
    name=name;
    weight=weight;
    name=value;
}

武器
#ifndef WEAPON_H
#define WEAPON_H
#include "item.h"
class Weapon : public Item
{
public:
  int damage;
  Weapon();
  Weapon(int damage);
};

#endif

武器库
#include <iostream>
#include <string>
#include <vector>
#include "weapon.h"
using namespace std;
Weapon::Weapon( damage): Item(name, weight, value){}

最佳答案

您需要在Item构造函数中显式指定所有Weapon参数。

像这样更改标题:

Weapon(int damage, string n, int w, int v);

像这样的实现:
Weapon::Weapon(int damage, string n, int w, int v): damage(damage), Item(name, weight, value){}

关于c++ - 为什么不能在派生类初始化时编译代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60268774/

相关文章:

c++ - 不应该像这样从 STL::list 中删除进入无限循环吗?

c++ - 什么是置换索引?

c++ - C++ 中的 Floyd 算法

Android:将 NdkMediaDrm 与 PlayReady 结合使用的文档

c++ - 在编译时将 std::array 的每个元素相乘

c++ - 递归查找优化

c++ - 在 C++ 中读取图像的像素

c++ - isDown() 与 isChecked() 的区别

c++ - 如何控制 beaglebone GPIO 引脚

c++ - qml无窗应用中如何设置拖拽区域