gpt4 book ai didi

c++ - 调用在基类中私有(private)的派生类的虚函数时出现访问说明符错误

转载 作者:行者123 更新时间:2023-11-30 01:10:18 25 4
gpt4 key购买 nike

为什么我会收到以下代码的访问说明符错误(私有(private)成员)?

#include<iostream>
using namespace std;

class Derived;

class Base {
private:
virtual void fun() { cout << "Base Fun"; }
};

class Derived: public Base {
public:
void fun() { cout << "Derived Fun"; } //this should be called
};

int main()
{
Base *ptr = new Derived;
ptr->fun();
return 0;
}

这里应该调用派生类的fun(),因为是public的,应该不会出错。

最佳答案

根据标准(N4140):

11.5 Access to virtual functions

1 The access rules (Clause 11) for a virtual function are determined by its declaration and are not affected by the rules for a function that later overrides it. [ Example:

class B {
public:
virtual int f();
};
class D : public B {
private:
int f();
};
void f() {
D d;
B* pb = &d;
D* pd = &d;
pb->f(); // OK: B::f() is public,
// D::f() is invoked
pd->f(); // error: D::f() is private
}

end example ]

顺便说一句,在一般情况下,在编译期间不可能知道在运行时将调用哪个类。

考虑

Base *ptr = GetBaseOrDerivedObject();
ptr->fun();

哪里GetBaseOrDerivedObject , 根据具体的运行时情况,可以返回一个指向 Base 类型对象的指针或 Derived .

关于c++ - 调用在基类中私有(private)的派生类的虚函数时出现访问说明符错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38212312/

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