c++ - 为什么 "virtuality"方法在 C++ 中隐式传播?

标签 c++ templates polymorphism virtual type-erasure

移除阻止方法虚拟性传播的能力的原因是什么?

让我更清楚一点:在 C++ 中,无论你在派生类中编写“virtual void foo()”还是“void foo()”,只要在基类中声明 foo,它就会是虚拟的。

这意味着通过派生* 指针调用 foo() 将导致虚拟表查找(如果派生2 函数覆盖 foo),即使程序员不希望这种行为。

让我举一个例子(对我来说看起来很明显),说明阻止虚拟传播有什么用处:

template <class T>
class Iterator // Here is an iterator interface useful for defining iterators
{              // when implementation details need to be hidden
public:
    virtual T& next() { ... }
    ...
};

template <class T>
class Vector
{
public:
    class VectIterator : public Iterator<T>
    {
    public:
        T& next() { ... }
        ...
    };
    ...
};

在上面的示例中,可以使用 Iterator 基类以更清晰和面向对象的方式实现“类型删除”的一种形式。 (有关类型删除的示例,请参见 http://www.artima.com/cppsource/type_erasure.html。)

但是,在我的示例中,可以直接使用 Vector::VectIterator 对象(在大多数情况下都会这样做),以便在不使用接口(interface)的情况下访问真实对象。

如果没有传播虚拟性,即使从指针或引用对 Vector::VectIterator::next() 的调用也不会是虚拟的,并且能够内联并高效运行,就像 Iterator 接口(interface)没有一样'不存在。

最佳答案

C++11 为此添加了上下文关键字final

class VectIterator : public Iterator<T>
{
public:
    T& next() final { ... }
    ...
};

struct Nope : VecIterator {
    T& next() { ... } // ill-formed
};

关于c++ - 为什么 "virtuality"方法在 C++ 中隐式传播?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13972462/

相关文章:

c++ - "Error: type name is not allowed"消息在编辑器中但在编译期间没有

templates - MailChimp 预览覆盖链接样式

PHP 最佳设计实践

c++ - 对引用使用多态性。非 const 引用的初始化无效

php - Laravel MorphToMany 不适用于多列

c++ - 如何确定 boost async_accept 是否正在监听端口

C++ 中的 Python lambda

c++ - 迭代器的模板参数 : function infers type when called?

C++ 模板 : When to include template parameters in templatized struct?

c# - 为什么这行得通?方法重载+方法覆盖+多态