是否有可能继承最终功能但创建相同功能(不覆盖)的派生类?
问题描述:
我有一个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
};
答
很抱歉,但它不可能在派生类中创建一个函数,当具有相同名称的功能存在作为基类final
。你需要重新考虑你的设计。
问题源于这样一个事实,即派生类中具有与基类中的函数相同名称的函数声明被视为覆盖override
关键字是否存在的尝试(由于历史原因,I假设)。所以你不能“关闭”覆盖。
这里有一个相关的标准报价:
§10.3/4 class.virtual]
如果在某些类
B
一个虚函数f
标有的virt-符final
和从B
派生的类D
函数D::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
};
末端
答
我觉得这是一个实验性的问题,因为其实你应该反思一下,你在做什么,当你需要为“超越最后的功能”(听起来矛盾,不是吗?)。
但是,您可以引入一个“虚拟”参数,即void NonFinal::print(int test=0)const
,它让编译器将成员函数视为不同的参数。不知道这是否能解决你的“问题”;但至少它引入了一个具有相同名称的函数,该函数仍然可以在不传递参数的情况下调用,并且与Derived
和Base
中的函数分开。
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..."
}
作为一般规则,我会调用隐藏继承成员的代码上的设计错误(显而易见的例外是覆盖继承的虚函数)。我会建议在'NonFinal'中调用其他方法。如果你发现自己需要这样做,那么关于你的OO设计的东西就不好。 – cdhowie