gpt4 book ai didi

c++ - 多重虚继承

转载 作者:行者123 更新时间:2023-11-30 05:37:57 24 4
gpt4 key购买 nike

我在工作时在我们的代码库中发现了以下代码,我觉得它看起来很奇怪。类 RetainCounting 用于实现引用计数。

1.IProvider真的应该派生自RetainCounting吗?如果它只是一个抽象基类,然后让实现 IProvider 的类(即 ProviderImpl)从“RetainCounting”派生(即,如果它需要保留/释放功能)不是更好吗?

2.如果我们认为IProvider应该派生自RetainCounting,为什么ProviderImpl还需要派生自“RetainCounting”,而IProvider已经有这个继承?

class RetainCounting
{
public:
virtual ~RetainCounting();
void retain();
void release();

private:
// more code....
};

class IProvider : public virtual RetainCounting
{
public:
virtual void doSomething() = 0;
};

class ProviderImpl : virtual private IProvider,
virtual public RetainCounting
{
public:
void doSomething() override;
};

最佳答案

2.If we believe that IProvider should derive from RetainCounting, why do ProviderImpl needs to derive from "RetainCounting" as well, when the IProvider already has this inheritance?

如果它必须公开继承 RetainCounting,那么它必须继承它,因为 IProvider - 并且传递它自己的 RetainCounting 基础 - 是私有(private)继承的.但是您可以非虚拟地继承 IProvider,除非某些东西继承了多个 IProvider 派生词。

如果不需要可见性差异,那么可以通过去掉虚继承,只继承IProvider来简化设计。

class IProvider : public RetainCounting

class ProviderImpl : public IProvider // or private, depending on what you need

1.Should the IProvider really derive from RetainCounting? Isn´t it better if it was just an abstract base class and then let the class that implements IProvider i.e. ProviderImpl derive from the "RetainCounting" instead (i.e. if it needs retain/release features)?

如果 IProvider 的所有派生类都不需要引用计数,那么 IProvider 不应该继承 RetainCounting 而应该只而是在导数中完成。

接口(interface)通常是指一个只有纯虚函数,没有成员变量的类。如果 IProvider 继承了一些不是接口(interface)的东西,那么它本身就不是接口(interface)。

如果 IProvider 的所有派生词都必须进行引用计数,但您希望 IProvider 成为一个接口(interface),例如通常以 I 为前缀名称,那么您可以做的是定义一个用于引用计数的接口(interface)。我们称它为 IRetainCounting。由于实现可能由许多衍生产品共享,因此您可以创建一个实现它的基类。这导致您需要虚拟继承。

class IRetainCounting
{
public:
virtual ~IRetainCounting(){}
virtual void retain() = 0;
virtual void release() = 0;
};

class RetainCounting: public virtual IRetainCounting
{
public:
void retain() override;
void release() override;

private:
// more code....
};

class IProvider : public virtual IRetainCounting
{
public:
virtual void doSomething() = 0;
};

// option 1
class ProviderImpl : private IProvider,
public RetainCounting
{
public:
void doSomething() override;
};

// option 2, you can keep BaseRetainCounting private if you want to
// I recommend this if there can be more than 1 implementation of IRetainCounting
// otherwise 1 is simpler
class ProviderImpl : private IProvider,
private RetainCounting,
public virtual IRetainCounting

优点:纯接口(interface)

缺点:代码更多(但数量不变。样板文件的数量不会随着衍生品的数量增加。)和虚拟继承的需要(无论如何你都需要虚拟继承来实现可见性差异)

关于c++ - 多重虚继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33032283/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com