c++ - 从派生类中删除虚函数

标签 c++ inheritance c++11 derived-class

我有一个虚拟基类函数,它永远不应该在特定的派生类中使用。有没有办法“删除”它?我当然可以给它一个空定义,但我宁愿尝试使用它会引发编译时错误。 C++11 delete 说明符似乎是我想要的,但是

class B
{
    virtual void f();
};

class D : public B
{
    virtual void f() = delete; //Error
};

不会编译;至少,gcc 明确不会让我删除具有未删除基本版本的函数。是否有其他方法可以获得相同的功能?

最佳答案

标准不允许这样做,但是您可以使用以下两种解决方法之一来获得类似的行为。

第一种是使用 using将方法的可见性更改为私有(private),从而防止其他人使用它。该解决方案的问题是,在父类(super class)的指针上调用该方法不会导致编译错误。

class B
{
public:
    virtual void f();
};

class D : public B
{
private:
    using B::f;
};

到目前为止,我发现在调用 Ds 方法时出现编译时错误的最佳解决方案是使用 static_assert 和继承自 false_type。只要没有人调用该方法,该结构就会保持未定义,并且 static_assert 就不会失败。

如果方法被调用,结构体被定义并且它的值为false,所以static_assert失败。

如果方法没有被调用,但是你试图在父类(super class)的指针上调用它,那么D的方法没有定义,你得到一个 undefined reference 编译错误。

template <typename T>
struct fail : std::false_type 
{
};

class B
{
public:
    virtual void f() 
    {
    }
};

class D : public B
{
public:
    template<typename T = bool>
    void
    f()
    {
        static_assert (fail<T>::value, "Do not use!");
    }
};

另一种解决方法是在使用该方法时抛出异常,但这只会在运行时抛出。

关于c++ - 从派生类中删除虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24609872/

相关文章:

C++ boost range adapter 多个 vector

c++ - 使用临时数组作为左值

c++ - 在 Fedora 21 上构建 butt

c# - 使用 C++/CLI 作为 'middleware' 使用 native C++ 中的 .NET 类

swift - 如何在 Swift 3 的子类之间共享变量?

c++ - 不可访问的基类

C++:重载不选择预期的方法

c++ - 创建从一种类型到另一种类型的别名

c++ - 使用iterator和reverse_iterator打印 vector 元素有没有更好的方法?

c++ - 字符串是 C++ 中的 char 吗?