如何定义从结构继承的静态变量
How do I define a static variable inherited from a struct?
我有一个头,里面有一个结构:
#ifndef CHARACTER_H_
#define CHARACTER_H_
#include <string>
using namespace std;
struct Character
{
string name;
static string type;
static int baseHp, baseAttack, baseDefence;
};
#endif
我有一个继承该标头的类,我想在继承类的结构中定义静态变量。假设我的继承类如下:
#include "Character.h"
#include <string>
class Rouge: private Character
{
public:
Rouge(string name)
{
this->name = name;
}
string getName()
{
return name;
}
};
在Rouge
类中,我将在哪里定义Character
标头中声明的静态变量,以及如何进行定义?
您将它们定义为Rouge
不存在;他们是Character
:的成员
string Character::type;
int Character::baseHp;
int Character::baseAttack;
int Character::baseDefence;
因此,如果您期望从Character
派生的每个类的这些值不同,那么您会感到失望:数据成员不能被"重写"。
相反,传统的做法是覆盖在基中声明但使成为纯虚拟的getter函数,这样Character
就变为纯函数,Rouge
必须覆盖这些函数,以便根据需要返回该特定类型的值。
实现固定值的一种简单方法是使用产生这些值的虚拟函数:
class Animal
{
public:
virtual
auto number_of_tails() const -> int { return 0; }
};
class Doggie
: public Animal
{
public:
auto number_of_tails() const -> int override { return 1; }
};
我希望我把override
关键字放对了。
如果您希望这些信息在没有类实例的情况下可用,只需用静态函数实现即可:
class Doggie
: public Animal
{
public:
auto number_of_tails() const -> int override { return the_number_of_tails(); }
static
auto the_number_of_tails() const -> int { return 1; }
};
免责声明:编译器从未接触过代码。
相关文章:
- 为什么除了继承聚合结构之外,结构为空,无法聚合初始化?
- 将继承的结构传递给 poll()
- 继承层次结构并将元素添加到向量
- 具有菱形继承结构的子类的大小似乎很奇怪
- 如何向类添加继承结构,请参阅"enable_share_on_this"
- 在C 中继承C结构并将其传递回C库是安全的吗?
- 来自无法识别的继承结构的本地声明
- 继承结构的类型转换导致g++编译错误
- C++ 将结构函数作为继承结构中函数的参数传递
- 私下继承结构
- 有没有办法避免在特定自定义类继承结构中使用虚拟方法
- 可以在C++中类继承结构
- 当使用代码块13.12时,Doxygen没有产生正确的继承结构
- C++11 中的 POD 和继承.结构的地址 == 第一个成员的地址
- 具有带函数指针的类私有成员的继承结构
- 这种c++继承结构可能吗?
- 重写采用继承结构的函数
- 此继承结构是否存在切片问题
- 如何从基类继承结构成员
- 如何在c++中创建继承结构时设置父成员