gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:33:07 27 4
gpt4 key购买 nike

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..."
}

关于c++ - 是否有可能有一个继承最终函数但创建相同函数(而不是重写)的派生类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44706215/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com