gpt4 book ai didi

c++ - 您可以覆盖基类中定义的私有(private)函数吗?

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

我相信,派生类只能覆盖它从基类继承的那些函数。我的理解对吗?

也就是说,如果基类有一个公共(public)成员函数func,那么派生类可以覆盖成员函数func

但是如果基类有一个私有(private)成员函数foo,那么派生类就不能覆盖成员函数foo

我说的对吗?

编辑

在研究了 SO 成员给出的答案后,我想出了一个代码示例。我提到了我在代码中作为注释研究的要点。希望我是对的。谢谢

/* Points to ponder:
1. Irrespective of the access specifier, the member functions can be override in base class.
But we cannot directly access the overriden function. It has to be invoked using a public
member function of base class.
2. A base class pointer holding the derived class obj's address can access only those members which
the derived class inherited from the base class. */

#include <iostream>

using namespace std;


class base
{
private:
virtual void do_op()
{
cout << "This is do_op() in base which is pvt\n";
}

public:
void op()
{
do_op();
}
};

class derived: public base
{
public:
void do_op()
{
cout << "This is do_op() in derived class\n";
}
};

int main()
{
base *bptr;
derived d;

bptr = &d;
bptr->op(); /* Invoking the overriden do_op() of derived class through the public
function op() of base class */
//bptr->do_op(); /* Error. bptr trying to access a member function which derived class
did not inherit from base class */

return 0;
}

最佳答案

无论访问说明符如何,您都可以覆盖函数。这也是 non-virtual interface 的核心成语。唯一的要求当然是它们是虚拟的

关于c++ - 您可以覆盖基类中定义的私有(private)函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8103827/

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