gpt4 book ai didi

c++ - 试图在C++中的子类中调用父类的 protected 函数

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

<分区>

我一直以为我懂继承,但显然我不懂。我想从子类调用同一父类的另一个实例的 protected 成员函数,如以下示例代码所示:

#include <iostream>

class Parent {
protected:
void doStuff(){
std::cout << 5 << std::endl;
}
};

class Child : public Parent {
public:
void pubfunc(Parent* p){
p->doStuff();
}
};

int main(){
Child* c = new Child();
Parent* p = new Parent();
c->pubfunc(p);
return 0;
}

但是,此代码的编译失败:

In member function ‘void Child::pubfunc(Parent*)’:
error: ‘void Parent::doStuff()’ is protected
error: within this context

我不想让 Child 类成为 Parent 类的 friend 以避免子类的前向声明和前向包含越多越好。另外,我不想将 doStuff 公开,因为在错误的情况下使用它确实会搞乱 Parent 的内部结构。

为什么会出现这个错误,最优雅的解决方法是什么?

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