繁体   English   中英

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

[英]why does the derived class could call the member function in the base class?

我的问题是,我有三个班,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的函数storedata可能不会调用类B的函数storedata,因为类B中的函数storedata被声明为具有访问控制private

所以编译器应该发出错误。

如果它将在具有publicprotected访问控制的B类中声明,则可以由C类调用它。 可以调用它,因为在类C的函数storedata中,调用指定了引用类B中函数storedata的限定名。

Functions declared in base class are also members of derived class. 如果派生类声明一个与基类中的函数同名的函数,则派生类中的函数会隐藏基类中的函数。 您可以通过使用引用基类中的函数的限定名称在派生类的某个方法中调用基类的函数。 并且功能是否为虚拟并不重要。

编辑:我看到你已阅读我的帖子并将私人访问控制更改为公共访问控制。:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM