是否有可能有一个派生类继承最终函数但创建相同的函数(不覆盖)?

l.i*_*.s. 5 c++ inheritance overriding virtual-functions final

我的final功能有问题.我想"停止"类中的多态,但我仍然想在派生类中生成相同的函数.

像这样的东西:

class Base{
    protected:
        int _x, _y;
    public:
        Base(int x = 0, int y = 0) : _x(x), _y(y){};
        int x() const { return _x; }
        int y() const { return _y; }
        virtual void print()const{ cout << _x*_y << endl; }
};

class Derived : public Base{
    public:
        Derived(int x = 0, int y = 0) : Base(x, y){}
        void print()const final { cout << _x*_y / 2.0 << endl; } // final inheritance
};

class NonFinal : public Derived{
        void print()const{ cout << "apparently im not the last..." << endl } 
    // here i want a new function. not overriding the final function from Derived class
};
Run Code Online (Sandbox Code Playgroud)

And*_*dyG 2

抱歉,当基类中存在同名函数时,无法在派生类中创建函数final。您需要重新考虑您的设计。

\n\n

问题源于这样一个事实:派生类中与基类中的函数同名的函数声明被视为尝试覆盖关键字是否override存在(我认为是出于历史原因)。所以你不能“关闭”覆盖。

\n\n

这是相关标准报价:

\n\n

\xc2\xa7 10.3/4 [类.虚拟]

\n\n
\n

f如果某个类中的虚拟函数用virt 说明符B标记,而在从函数overrides派生的类中,则该程序是格式错误的。[ 例子: finalDBD::fB::f

\n
\n\n
struct B {\n   virtual void f() const final;\n};\nstruct D : B {\n   void f() const; // error: D::f attempts to override final B::f\n};\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n

\xe2\x80\x94end

\n
\n