gpt4 book ai didi

c++ - 为什么派生类可以调用基类的成员函数?

转载 作者:行者123 更新时间:2023-11-28 02:55:12 27 4
gpt4 key购买 nike

我的问题是,我有三个类,A 是抽象类。 B 派生自 A,然后 C 派生自 B。

我只是列出了我有疑问的功能。

class A{
public:virtual void storedata(int a, int b, int c, int d)=0;
}

B.h
class B: public A{
public:virtual void storedata(int a, int b, int c, int d);
}
B.cpp
void storedata(int a, int b, int c, int d)
{ do something }

C.h
class C: public B{
public:virtual void storedata(int a, int b, int c, int d);
}

C.cpp
void storedata(int a, int b, int c, int d)
{
B::storedata(int a, int b, int c, int d);
}

为什么派生类C可以调用C.cpp中的B::storedata?

最佳答案

为什么不能呢?覆盖虚函数的目的是允许您自定义派生类型对象的行为,但有时所需的行为包括执行基类所做的处理,可能有条件地或使用一些前或后操作。事实上,你可以提供纯虚函数的实现,这主要是为了让派生类可以在合适的时候方便地调用抽象基类的实现。在这种情况下,覆盖是无用的,因为它只做 B 版本所做的事情,但通常允许调用 B 版本可能有用。

关于c++ - 为什么派生类可以调用基类的成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22159612/

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