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

Is it possible to have a derived class that inherits a final function but creates the same function (not override)?

本文关键字:函数 重写 派生 有一个 有可能 继承 是否 创建      更新时间:2023-10-16

我对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
};
我认为

这是一个实验性问题,因为实际上当你需要"覆盖最终函数"时,你应该重新考虑你在做什么(听起来很矛盾,不是吗?

但是您可以引入一个"虚拟"参数,即 void NonFinal::print(int test=0)const,这让编译器将成员函数视为不同的函数。不确定这是否解决了您的"问题";但至少它引入了一个同名的函数,它仍然可以在不传递参数的情况下调用,并且与 DerivedBase 的函数分开

class NonFinal : public Derived{
public:
    void print(int test=0)const{ cout << "apparently im not the last..." << endl; }
};
int main() {
    Base b (10,10);
    Derived d (20,20);
    NonFinal nf;
    Base *bPtr = &d;
    bPtr->print();  // gives 200
    bPtr = &nf; // gives 0
    bPtr->print();
    nf.print(); // gives "apparantly..."
}

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

问题源于这样一个事实,即派生类中的函数声明与基类中的函数同名被视为试图覆盖 override 关键字是否存在(我认为是出于历史原因(。因此,您无法"关闭"覆盖。

以下是相关的标准报价:

§ 10.3/4 [虚拟类]

如果某个类B中的虚函数fvirt 说明符final标记,而在从B派生的类DD::f覆盖B::f,则程序格式不正确。[ 示例:

struct B {
   virtual void f() const final;
};
struct D : B {
   void f() const; // error: D::f attempts to override final B::f
};

—完