C++ 函数 = 删除

标签 c++ class oop inheritance polymorphism

在 C++ 中(我相信自 C++ 11 起),只要程序员不希望编译器自动实现默认构造函数或赋值运算符,就可以“删除”构造函数或赋值运算符。

例如,可以,

class a
{
    const a& operator=(const a& copy_me) = delete;
}

这将删除默认赋值运算符。编译器不会为我们实现默认的 operator=。我们根本无法在我们的代码中使用它,它就好像它从未存在过一样。

考虑一个具有函数、虚函数和纯虚函数的抽象基类(或只是一个基类)。

class example_base
{
    void function()
    {
        return;
    }

    virtual
    void virtual_function() // Do we have to provide an implementation?
    {
        return;
    }

    virtual
    void pure() = 0; // Are there other ways to declare a pure virtual?
                     // Can pure() have an implementation in this class?
}

如果另一个类继承自基类,是否允许我们“删除”基类中提供的一些功能? (Q1)

如果是这样,它的规则和效果是什么? (Q2)

如果后续类继承自 example_inherits 并且我们删除了一些成员函数,会发生什么情况?我们可以再次使用它们吗? (Q3)

class example_inherits : example_base
{
    void function() = delete; // Allowed?

    virtual
    void virtual_function() = delete; // If so why ...

    virtual
    void pure() = delete; // ... or why not?
}

Q3 的例子:

class another : example_inherits
{
    // Allowed to use deleted function?
    void function()
    {
        std::cout << "blaa" << std::endl;
    }
}

您可能会想到我所描述内容的其他排列,例如实现一个低 2 继承顺序的已删除方法。 (即,在一个继承自一个类的类中,该类继承自一个类...)

或者虚拟/纯虚拟排序的不同选择......例如:一个类有一个虚拟纯,一些东西继承自这个类并继承与虚拟相同的功能,然后另一个继承自这个类要么删除它要么实现它作为一个常规函数......等等......

我将不胜感激 - 我无法在网上找到如此详细的信息。

最佳答案

嗯,您在这里有很多问题。他们都可以通过尝试得到答案:)

We simply will not be able to us it in our code, it will be as if it was never there

不完全是,因为删除的版本参与了重载决议。例如:

void f(long);
void f(int) = delete;

f(5);

这将无法编译,但是如果您注释掉 =delete 版本,那么它会编译。


继续您的问题。

Can pure() have an implementation in this class?

是的,= 0 只意味着派生类必须覆盖它。但是您仍然可以在同一个类中为该函数提供一个外联定义。

void function() = delete; // Allowed?

是的,这是允许的。派生的 function() 隐藏了基础 function(),因为它不是虚拟的。当然,您仍然可以通过指针或对基类的引用来调用基函数

void virtual_function() = delete;

这是不允许的;虚函数不能被删除。

关于C++ 函数 = 删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31636126/

相关文章:

c++ - 如何关联具有不同名称的依赖 vcproj 文件中的构建配置?

c++ - 如何在 C++11 中初始化未在其构造函数中初始化其所有成员的类

c++ - 如何在特定时间后终止递归函数?

c++ - 未定义对 'class::function' 的引用?

java - 哪个 Web 服务堆栈允许将 wsdl first Web 服务绑定(bind)到 Java 中的现有类?

c++ - 用direct2d创建位图图集, "current bitmap"指的是什么?

Python - 我可以访问给我打电话的对象吗?

c++ - 从 Qt Creator 构建 osgEarth 应用程序

python - 传递给 Python 中所有实例方法的预处理参数

javascript - 如何在 Javascript 和 OOP 中创建方法