是否有可能有一个派生类继承最终函数但创建相同的函数(而不是重写)
Is it possible to have a derived class that inherits a final function but creates the same function (not override)?
我对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
,这让编译器将成员函数视为不同的函数。不确定这是否解决了您的"问题";但至少它引入了一个同名的函数,它仍然可以在不传递参数的情况下调用,并且与 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..."
}
抱歉,当存在与基类中final
同名的函数时,无法在派生类中创建函数。您需要重新考虑您的设计。
问题源于这样一个事实,即派生类中的函数声明与基类中的函数同名被视为试图覆盖 override
关键字是否存在(我认为是出于历史原因(。因此,您无法"关闭"覆盖。
以下是相关的标准报价:
§ 10.3/4 [虚拟类]
如果某个类
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
};
—完
相关文章:
- 在 C++ 中用派生类型重写成员函数
- 重写虚拟函数和继承
- C++调用使用重写函数的父类函数
- 重写打印函数而不是覆盖基类
- 重写函数不打印基类数据
- 将一个小的 C 定义重写为"normal" C++函数
- 重写另一个方法 [C++] 使用的超类回调函数
- 具有派生参数的函数重写
- 在回调中使用函数时,C++未知重写说明符
- 用模板化函数重写虚拟函数
- 没有函数重写的多重继承.为什么模棱两可
- C++ 继承构造函数重写
- 关于C++中的虚拟函数重写
- C++函数重写不起作用
- 如何实现类变量的虚拟函数重写
- 将C++函数重写为C#(将指针传递到数组中的下一个元素)
- 引用可以用于实现函数重写吗
- 用函数重写嵌套的if-else语句
- C++继承函数重写
- 本机C++中的函数重写