问题
This isn't an actual programming question, I just need advice on how to structure a part of my program.
The program is divided into a client and a server part. Both share certain code, including base classes. Here's a representation of the code I'm having trouble with:
Shared classes:
class BaseEntity
{
public:
virtual void EmitSound(std::string snd) {}
virtual bool IsPlayer() {return false;}
};
class BasePlayer
: public BaseEntity
{
public:
bool IsPlayer() {return true;}
}
Serverside classes:
class Entity
: public BaseEntity
{
public:
void EmitSound(std::string snd)
{
// Serverside implementation
}
}
class Player
: public Entity,BasePlayer
{
public:
void Kick() {}
}
Clientside classes:
class CEntity
: public BaseEntity
{
public:
void EmitSound(std::string snd)
{
// Clientside implementation
}
};
class CPlayer
: public CEntity,BasePlayer
{
public:
void SetFOV() {}
}
(The methods are just examples)
The class 'Player' should inherit all members from both 'Entity' and 'BasePlayer'. This doesn't work however, since both have the same parent class (BaseEntity).
I could of course remove the inheritance from 'BasePlayer' but then I'd end up with two 'IsPlayer' functions, each returning something different.
I could also move all members from 'BasePlayer' into 'Player' and 'CPlayer' respectively, but that'd lead to redundancy I'd like to avoid and I'd no longer be able to use a single pointer for objects of either class while keeping access to all shared methods.
I don't like either of these solutions, but I can't think of anything else. Is there an optimal solution to this problem?
回答1:
the simplest solution i see that i think would solve your specific problem would be to have class BasePlayer not inherit from class BaseEntity.
class Player will end up with the BaseEntity class characteristics because it inherits from class Entity which inherits from class BaseEntity, and class CPlayer will end up with BaseEntity class characteristics because it inherits from class CEntity which inherits from class BaseEntity.
来源:https://stackoverflow.com/questions/16874180/structuring-classes-with-multiple-inheritance