我是 C++ 的新手。我有简单的单元类和继承单元类的英雄类。 Hero 类有 2 个附加参数,但构造函数无法访问父类的参数。 这是 unit.hpp:
#ifndef UNIT_HPP
#define UNIT_HPP
#include <string>
using namespace std;
class Unit
{
public:
unsigned short max_health = 100;
string name = "Dummy";
short health = 100;
short damage = 10;
bool isDead = 0;
Unit();
Unit(string, unsigned short, unsigned short);
};
#endif //UNIT_HPP
这里是 unit.cpp:
#include <string>
#include <iostream>
#include "unit.hpp"
using namespace std;
Unit::Unit()
{
cout << "Dummy was created!" << endl;
};
Unit::Unit(string N, unsigned short HP, unsigned short AT):
max_health(HP),
name(N),
health(HP),
damage(AT)
{
cout << N << " was created!" << endl;
};
这里是 hero.hpp:
#ifndef HERO_HPP
#define HERO_HPP
#include <string>
#include "unit.hpp"
class Hero : public Unit
{
public:
unsigned short max_mana = 100;
string name = "The Brave Warrior";
short mana = 100;
Hero (string, unsigned short, unsigned short, unsigned short);
};
#endif //HERO_HPP
最后,这是 hero.cpp:
#include <string>
#include "hero.hpp"
using namespace std;
Hero::Hero(string N, unsigned short HP, unsigned short MP, unsigned short AT):
max_health(HP),
max_mana(MP),
name(N),
health(HP),
mana(MP),
damage(AT)
{
cout << "The Legendary Hero, " << N << ", was born!" << endl;
}
这是控制台输出:
src/hero.cpp: In constructor ‘Hero::Hero(std::__cxx11::string, short unsigned int, short unsigned int, short unsigned int)’:
src/hero.cpp:10:5: error: class ‘Hero’ does not have any field named ‘max_health’
max_health(HP),
^
src/hero.cpp:13:5: error: class ‘Hero’ does not have any field named ‘health’
health(HP),
^
src/hero.cpp:15:5: error: class ‘Hero’ does not have any field named ‘damage’
damage(AT)
^
问题出在哪里?抱歉英语不好。我希望我问的问题对,对我来说有这么多新术语。先感谢您。
最佳答案
您的基类通常应负责通过构造函数 方法初始化其变量。
这个:
unsigned short max_health = 100;
string name = "Dummy";
short health = 100;
short damage = 10;
bool isDead = 0;
看起来不符合犹太洁食标准。这些成员应该在构造函数中初始化:
Unit::Unit()
: max_health(100),
name("Dummy"),
health(100),
damage(10),
isDead(false)
{ ; }
此外,对于 bool
变量,您应该使用 true
或 false
,而不是数字。
编辑 1:成员名称重复
您的子类应避免使用与基类相同的变量名。
英雄中的那一行:
string name;
遮蔽或隐藏基类成员:
string name;
如果您更愿意遵守此约定,您应该使用作用域解析运算符 ::
来告诉编译器您指的是哪个成员:
Hero::name = "Hercules"; // Assign member in Hero class
Unit::name = "Person"; // Assign to member in Unit class.
关于c++ - 无法在构造函数中访问类的继承成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38061852/