本文介绍了C ++将public纯虚拟方法覆盖为public的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么会这样?

http://coliru.stacked-crooked.com/a/e1376beff0c157a1

class Base{
private:
    virtual void do_run() = 0;
public:
    void run(){
        do_run();
    }
};

class A : public Base {
public:
    // uplift ??
    virtual void do_run() override {}
};


int main()
{
    A a;
    a.do_run();
}

为什么我可以将 PRIVATE 虚拟方法覆盖为公共方法?

Why can I override a PRIVATE virtual method as public?

推荐答案

根据 https://en.cppreference.com/w/cpp/language/virtual#In_detail 覆盖基础的virtual成员函数,仅关心函数名称,参数,const/volatile-ness和ref限定符.它不在乎返回类型,访问修饰符或其他您可能希望它关心的东西.

According to https://en.cppreference.com/w/cpp/language/virtual#In_detail overriding a base's virtual member function only care about the function name, parameters, const/volatile-ness and ref qualifier. It doesn't care about return type, access modifier or other things you might expect it to care about.

链接的参考文献还特别指出:

The linked reference also specifically notes that :

我找不到任何明确允许执行此操作的权限,但是覆盖规则并未阻止它.借助于virtual函数以及覆盖现有函数且不禁止这种情况的函数是允许的.

Nothing that I can find explicitly gives permission to do this, but the rules of overriding do not prevent it. It's allowed by virtue of virtual functions and function overriding existing and not disallowing this case.

如果您要问为什么这是哪种语言,则可能需要询问标准化委员会.

If you are asking why this is how the language is, you may have to ask the standardization committee.

这篇关于C ++将public纯虚拟方法覆盖为public的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 11:50