我正在写一个2D游戏并希望从一开始就做好。我不完全确定如何解决多重继承和转换。
让我们说比如我有一个游戏世界。我创建了一个名为 Environment 的类,所有对象都将继承该类。
现在,如果我创建另一个名为Brick and Ground的类,这两个类将继承环境中的函数。现在让我们说我希望能够在接触时爆炸Brick,但是地面阶层不会使用它,所以在环境类中创建类似的函数并将其变为虚拟将是一种浪费。 / p>
所以我可能,如果我将环境对象转换回派生类并从那里调用它的函数:(下面仅举例说明虽然过程)
#include <iostream>
#include <string>
#include <vector>
#include <limits>
class Environment
{
protected:
std::string name;
int health;
int damage;
public:
Environment(std::string _name)
{
this->name = _name;
}
virtual std::string GetType() = 0;
std::string GetName()
{
return this->name;
}
void Spawn()
{
std::cout << this->name << ": Spawning object..." << std::endl;
}
int GetHealth()
{
return this->health;
}
void TakeDamage(int _damage)
{
this->health-=_damage;
}
virtual void Update() = 0;
virtual void Render() = 0;
virtual ~Environment(){}
};
class Ground : public Environment
{
private:
public:
Ground(std::string _name) : Environment(_name)
{
}
std::string GetType()
{
return "Ground";
}
void Update()
{
std::cout << "Updating: " << this->name << std::endl;
}
void Render()
{
}
};
class Brick : public Environment
{
private:
public:
Brick(std::string _name) : Environment(_name)
{
this->name = "Brick Ansikte";
this->health = 100;
}
std::string GetType()
{
return "Brick";
}
void Update()
{
std::cout << "Updating: " << this->name << std::endl;
}
void Render()
{
}
void Explode()
{
std::cout << "Exploding BRICK" << std::endl;
}
};
int main()
{
std::vector<Environment*> listEnvironment;
listEnvironment.push_back(new Ground("Ground fool"));
listEnvironment.push_back(new Brick("Ground tun"));
for(auto& env : listEnvironment)
{
std::cout << "HP: " << env->GetHealth() << std::endl;
env->Spawn();
env->Update();
if (env->GetType() == "Brick")
{
std::cout << "BRICK TYPE WAS FOUND, DYNAMIC CAST" << std::endl;
static_cast<Brick*>(env)->Explode();
}
delete env;
}
listEnvironment.empty();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
return 0;
}
这个解决方案好还是坏?或者我应该创建另一个基本辅助类,它包含游戏中可能发生的所有不同类型的操作?喜欢爆炸,弹跳等等?
祝你好运 尼罗