C ++ - 从另一个类构造函数

时间:2018-06-09 22:08:12

标签: c++ oop constructor c++14 encapsulation

所以我接受了一个c ++课程,并且在一个例外我需要在名为“Character”的类的构造函数中使用名为“Weapon”的类的构造函数,但每次当我尝试编译它给出的代码时我这个错误:

Character.cpp|13|error: no match for call to `(Weapon) (int&,std::__cxx11::string&)’|

即使我在Weapon.h中声明了这个确切的构造函数:

#ifndef WEAPON_H
#define WEAPON_H

#include <string>

class Weapon
{
public:
    Weapon();
    Weapon(int damage, std::string name);
    virtual ~Weapon();

    int GetDamage() { return m_damage; }
    void SetDamage(int val) { m_damage = val; }
    std::string GetName() { return m_name; }
    void SetName(std::string val) { m_name = val; }

private:
    int m_damage;
    std::string m_name;
};

#endif // WEAPON_H

顺便说一下,我是法国人,这是我第一次发帖,但我尽力用英语翻译源代码,如果某些行背后有任何错误或无意义的意思,请对不起。这是我的Character.cpp / Weapon.cpp / Character.h文件。

#include "Character.h"
#include "Weapon.h"

Character::Character()
{
    m_health_points = 100;
    m_mana = 100;
}

Character::Character(int damage, std::string name)
{
    m_health_points = 100;
    m_mana = 100;
    m_weapon(damage, name);
}

Character::~Character()
{
}
#include "Weapon.h"

Weapon::Weapon()
{
}

Weapon::Weapon(int damage, std::string name)
{
    m_damage = damage;
    m_name = name;
}

Weapon::~Weapon()
{
}
#ifndef CHARACTER_H
#define CHARACTER_H

#include "Weapon.h"

class Character
{
public:
    Character();
    Character(int damage, std::string name);
    virtual ~Character();

    int GetHealthPoints() { return m_health_points; }
    void SetHealthPoints(int val) { m_health_points = val; }
    int GetMana() { return m_mana; }
    void SetMana(int val) { m_mana = val; }

private:
    int m_health_points;
    int m_mana;
    Weapon m_weapon;
};

#endif // CHARACTER_H

3 个答案:

答案 0 :(得分:3)

C ++在构造函数中有成员变量初始化的特殊构造:

Character::Character(int damage, std::string name)
  : m_weapon(damage,name),
    m_health_points(100),
    m_mana(100)  
{
}

答案 1 :(得分:1)

m_weapon(damage,name);

在这里,您尝试在成员变量operator(int, std::string)上调用运算符m_weapon。没有定义这样的运算符。切换到:

Character::Character(int damage, std::string name)
   : m_weapon(damage,name)
{
   m_health_points=100;
   m_mana=100;
}

答案 2 :(得分:0)

/您不需要声明任何武器类值。你需要像这样初始化字符构造函数__.../

Character::Character(int damage, std::string name)
    : Weapon(damage,name),
{
}