本文介绍了允许模拟类从最终类继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以使用新的 C++ 关键字 final 声明一个 final/密封的不可继承类.

We may declare a final/sealed non-inheritable class using the new C++ keyword final.

class Generator final
{

};

这个类可能继承自其他类,可能有也可能没有虚拟(继承与否).但是,如何使它final,同时允许一个类继承它呢?

This class may inherit from other, may or may not have virtual (inherited or not). But, how to make it final, yet allow one class to inherit from it?

我们主要需要从真实类派生出一个模拟类(有或没有后期绑定,因此 virtual 并不重要).如何使它工作:

We mostly need to derive a mock class from real class (with or without late-binding, hence virtual isn't important). How to make it work:

class MockGenerator : Generator{};

但不允许任何其他继承?

But disallow any other inheritance?

推荐答案

这不可能.

我们主要需要从真实类派生出一个模拟类(有或没有后期绑定,因此虚拟并不重要).

如果类是最终的,您不需要从它派生.如果您确实需要从中派生,它不是最终的.选择一个.

If the class is final, you do not need to derive from it. If you do need to derive from it, it is not final. Pick one.

编辑:您可以向您的类添加限制,但这些限制会影响界面:

Edit: You can add restrictions to your class, but those come at their own cost to the interface:

class Generator // not final
{
    Generator(); // the only accessible constructor is private

    // whitelist who has access to this constructor
    friend class MockGenerator;
public:
    // no public constructors here except for copy & move

    Generator(Generator&);
    Generator(Generator&&);
    ...

    // provide controlled access to the private constructor
    static Generator make_generator() { return Generator(); }

    // rest of API here
};

这是一个允许它的工厂和 MockGenerator 特化调用它的构造函数的类.但是,这是以阻止琐碎构造为代价的.

This is a class that allows it's factory and MockGenerator specializations to call it's constructor. This comes at the price of blocking trivial construction though.

旧代码(不再可编译):

Old code (no longer compilable):

Generator instance;

新代码(由私有构造函数强制执行):

New code (enforced by the private constructor):

auto instance = Generator::make_generator();

这篇关于允许模拟类从最终类继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 01:28