【发布时间】:2013-06-01 15:17:56
【问题描述】:
这不是一个实际的编程问题,我只需要关于如何构建我的程序的一部分的建议。
程序分为客户端和服务器部分。两者共享某些代码,包括基类。这是我遇到问题的代码的表示:
共享课程:
class BaseEntity
{
public:
virtual void EmitSound(std::string snd) {}
virtual bool IsPlayer() {return false;}
};
class BasePlayer
: public BaseEntity
{
public:
bool IsPlayer() {return true;}
}
服务器端类:
class Entity
: public BaseEntity
{
public:
void EmitSound(std::string snd)
{
// Serverside implementation
}
}
class Player
: public Entity,BasePlayer
{
public:
void Kick() {}
}
客户端类:
class CEntity
: public BaseEntity
{
public:
void EmitSound(std::string snd)
{
// Clientside implementation
}
};
class CPlayer
: public CEntity,BasePlayer
{
public:
void SetFOV() {}
}
(这些方法只是示例)
“Player”类应该继承“Entity”和“BasePlayer”的所有成员。但是这不起作用,因为两者都有相同的父类 (BaseEntity)。
我当然可以从“BasePlayer”中删除继承,但最终会得到两个“IsPlayer”函数,每个函数都返回不同的东西。
我还可以将所有成员分别从“BasePlayer”移动到“Player”和“CPlayer”,但这会导致我想避免的冗余,并且我不再能够使用单个指针任一类的对象,同时保持对所有共享方法的访问。
我不喜欢这两种解决方案,但我想不出其他任何方法。 这个问题有最优解吗?
【问题讨论】:
-
一个“实体”的目的是什么,为什么Player必须从它继承,以及BasePlayer需要从BaseEnttity继承?对我来说,这似乎是不同类的混合,而不是“它应该是的方式”。
标签: c++ structure multiple-inheritance base-class