构建具有多重继承的类 [英] Structuring classes with multiple inheritance

查看:94
本文介绍了构建具有多重继承的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不是一个实际的编程问题,我只需要有关如何构成程序一部分的建议.

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:

共享课程:

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).

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).

我当然可以从'BasePlayer'中删除继承,但是最后我得到了两个'IsPlayer'函数,每个函数都返回不同的内容.

I could of course remove the inheritance from 'BasePlayer' but then I'd end up with two 'IsPlayer' functions, each returning something different.

我也可以将所有成员分别从'BasePlayer'移到'Player'和'CPlayer',但这会导致冗余,我想避免,并且我将不再能够使用单个指针任一类的对象,同时保留对所有共享方法的访问权限.

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?

推荐答案

最简单的解决方案是我认为可以解决您的特定问题的方法是让BasePlayer类不继承自BaseEntity类.

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最终将具有BaseEntity类特征,因为它继承自从BaseEntity类继承的Entity类,而CPlayer最终将具有BaseEntity类特征,因为它继承了从BaseEntity类继承的CEntity类.

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.

这篇关于构建具有多重继承的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆