gpt4 book ai didi

c++ - 派生类虚方法调用基类虚方法

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:04:27 24 4
gpt4 key购买 nike

在 C++ 中 - 假设派生类派生自基类,并且基类中有一个虚拟方法被派生类覆盖。谁能告诉我一个现实生活场景,其中派生类版本的虚函数可能需要调用基类版本的虚函数?

例子,

class Base
{
public:
Base() {}
virtual ~Base() {}
virtual void display() { cout << "Base version" << endl; }
};

class Derived : public Base
{
public:
Derived() {}
virtual ~Derived() {}
void display();
};

void Derived::display()
{
Base::display(); // a scenario which would require to call like this?
cout << "Derived version" << endl;
}

最佳答案

每当您还需要基类行为但不想(或不能)重新实现它时,您就会这样做。

一个常见的例子是序列化:

void Derived::Serialize( Container& where )
{
Base::Serialize( where );
// now serialize Derived fields

}

你不关心基类是如何序列化的,但你肯定希望它序列化(否则你会丢失一些数据),所以你调用基类方法。

关于c++ - 派生类虚方法调用基类虚方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7644154/

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