是否可以使用静态构造函数初始化式
Is a static constructor initializer possible?
考虑以下类。(从一个游戏,但大大简化)
combat.h:
class Combat {
public:
Combat();
Combat(int health, int offense, int defense);
virtual ~Combat();
int attack();
int defend();
int health() const;
void setHealth(int health);
private:
struct CombatImpl;
std::unique_ptr<CombatImpl> _impl;
};
combat.cc:
struct Combat::CombatImpl {
CombatImpl();
CombatImpl(int health, int offense, int defense);
~CombatImpl()=default;
int _health;
int _offense;
int _defense;
};
Combat::Combat(int health, int offense, int defense) :
_impl { new Combat::CombatImpl(health, offense, defense) } {
}
Combat::~Combat()=default;
int Combat::attack() {
int hits = 0;
for(int i = 0; i < _impl->_offense; i++ ) {
if (rand() % 6 == 5) {
hits++;
}
}
return hits;
}
int Combat::defend() {
int parries = 0;
for(int i = 0; i < _impl->_defense; i++ ) {
if (rand() % 6 == 5) {
parries++;
}
}
return parries;
}
int Combat::health() const {
return _impl->_health;
}
void Combat::setHealth(int health) {
_impl->_health += health;
}
Combat::CombatImpl::CombatImpl(int health, int offense, int defense) {
_health = health;
_offense = offense;
_defense = defense;
}
monster.h:
class Monster: public Combat {
public:
Monster(int health, int offense, int defense);
virtual ~Monster();
}
monster.cc:
Monster::Monster(int health, int offense, int defense)
: Combat(health, offense, defense) {}
Monster::~Monster()=default;
player.h:
class Player : public Combat {
public:
Player();
virtual ~Player();
private:
struct PlayerImpl;
static PlayerImpl _impl;
};
player.cc:
struct Player::PlayerImpl {
PlayerImpl()=default;
~PlayerImpl()=default;
} Player::_impl;
Player::Player() : Combat(17, 1, 1) {
}
Player::~Player()=default;
…最后,一个使用它们的测试程序:
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <memory>
using namespace std;
#include "monster.h"
#include "player.h"
static Monster monster(3, 1, 1);
void fight() {
Player player;
int damage = monster.attack();
damage -= player.defend();
if ( damage > 0 ) {
player.setHealth(-damage);
}
if ( player.health() < 1 ) {
return;
}
damage = player.attack();
damage -= monster.defend();
if ( damage > 0 ) {
monster.setHealth(-damage);
}
if ( monster.health() < 1 ) {
return;
}
}
int main() {
Player player;
srand(time(NULL));
while (player.health() > 0 && monster.health() > 0) {
fight();
printf("player health = %d monster health = %dn", player.health(),
monster.health());
}
}
如果你运行这个程序,你会发现它不起作用。怪物的生命值减少了,但玩家的生命值却停留在初始值上。我认为发生这种情况的原因是这样的;玩家只有静态数据(封装在PlayerImpl _impl)这是这样的,我可以有一个全局播放器对象,我可以从不同的函数在我的代码调用。(单态模式)但它的基类Combat是动态的。每次我创建playerplayer;在fight()中,我实际上得到了一个新的Combat,其中Combat::_health是默认值。当玩家离开范围时,任何对生命值的改变都会丢失。在monster中,这不是问题,因为monster对象也有动态数据。理想情况下我可以说
class Player : public static Combat {
表示只在这个特定的战斗中设置static,但这是一个语法错误。还有别的方法吗?还是我把自己逼入了死角?
听起来您还没有真正考虑过您的封装层次结构。从战斗中获得玩家并没有多大意义,而你的执行混乱(以及这个问题)也支持了这一点。你已经与c++提供给我们多重继承而不是接口的事实发生了冲突,因为我相信你试图描述的是玩家有一个战斗界面。
清理这类问题的一个常见方法是使用转发器/桥接/委托/trait/访问器类,在这种情况下可能是"Combatant"或"CombatHandler"或"CombatEntity"——所有这些都取决于你希望如何读取继承——其唯一目的是帮助你遍历封装图;在这种情况下,从一个实体到该类实体的战斗功能的封装。
这些中间类并不简单,仅限于互连逻辑。不要在里面放任何实际的功能;尽量保持所有成员为const。
class Combatant {
public:
Combatant() {}
virtual const Combat* Combat() const = 0; // so combat is technically our impl
virtual Combat* Combat() = 0;
// keep this interface light, it's primarily an accessor interface.
virtual bool CanFight() const { return (Combat() != nullptr); }
virtual bool CanFight(Combatant* opponent_) const {
return (opponent_ != nullptr && CanFight() && opponent_->CanFight());
}
};
class PassiveEntity() : Combatant {
...
const Combat* Combat() const { return nullptr; }
Combat* Comat() { return nullptr; }
}
class Player : public Combatant {
public:
virtual const Combat* Combat() const override {
// if you HAVE to use a static, something like this.
return &s_playerCombatImpl;
}
virtual Combat* Combat() override {
// but really it should be a member so it can be stateful.
return &m_combat;
}
...
};
class Monster : public Combatant {
...
};
class Corpse : public PassiveEntity {
...
};
你应该重构的第二件事是导致你调用不带参数的全局函数而不是调用
的原因。monster.fight(player);
//or
player.fight(monster);
我怀疑这是因为你试图实现帧,但还没有封装它,所以帧不知道参与者是谁,你强迫它通过使用全局变量。
重新审视你的原作,并回顾静态的使用是如何迫使你的手进一步往下走的:将战斗细节和意识提升到玩家类中,进一步打破你的封装。
这并不是说单例或全局必须不惜一切代价避免,只是确保你检查自己-你真的是说这个信息是可见的和可修改的任何类,包括"PrawnShriveller"answers"MP3Player",以及全局函数"WhenIdleFormatHardDriveCatchFireOrDoOtherThings()"?
- 为什么std::vector和std::valarray初始化构造函数不同
- 初始化构造函数C++中结构的向量
- C++ 中常量属性的初始化构造函数错误
- 不正确的输出和变量未用Eclipse CDT初始化构造函数
- 如何使用嵌套初始化构造函数中的一维向量初始化矩阵
- 如何通过参数初始化构造函数中的数组?
- 是否有理由使用 malloc 初始化构造函数中的指针
- 如何在 c++ 中初始化构造函数中的二维数组
- 为什么初始化构造函数列表参数时会发生异常?
- 无法初始化构造函数
- 初始化构造函数的默认参数的优选方法是什么?
- 在C++17中使用空列表初始化构造函数时发生编译错误
- C++ 初始化构造函数初始化列表中的嵌套结构?
- 初始化构造函数c++中的向量
- g++ (GCC) 4.6.0 我有以下类,我正在尝试初始化构造函数的结构成员初始化列表
- 使用字符串文本初始化构造函数中的 std::array<char,x> 成员。海湾合作委员会错误?
- 初始化构造函数C++中函数的成员指针
- 在c++中初始化构造函数中的静态成员变量时出错
- memset()初始化构造函数中的对象
- 初始化构造函数C++中的成员向量