简体   繁体   中英

C++ - Calling a class constructor from another class constructor

So I'm folowing a c++ course and on one excerise I need to use the constructor of a class named "Weapon" inside the constructor of a class named "Character" but each time when I try to compile the code it gives me this error :

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

even though I declared this exact constructor inside 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

Btw I'm French and it's my first time posting but I tried my best to translate the source code in english sorry if there's any mistakes or unintended meanings behind certain lines. Here are my Character.cpp / Weapon.cpp / Character.h files.

#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

C++ has special construct for member variable initialization in constructors:

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

Here, you are trying to call an operator operator(int, std::string) on a member variable m_weapon . There is no such operator defined. Switch to:

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

/ you don't need to declare any Weapon class valus. You need to initialize the character constructor like this__... /

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM