gpt4 book ai didi

C++如何创建创建派生类对象的基类,并访问基类的私有(private)成员?

转载 作者:太空宇宙 更新时间:2023-11-04 15:00:51 26 4
gpt4 key购买 nike

有什么方法可以让派生类访问基类private成员,同时能够在 base class 中的 base class 方法上创建 derived 对象吗?

像这样:

class Derived;

class Base
{
public:
void func()
{
// I want to create the derived obj here
Derived derived;
derived.func();
}
public:
int mBase = 5;
};

class Derived : public Base
{
public:
void func()
{
// I need to have access to the private members of Base inside this method
mBase = 6;
}
};

错误如下:

Error: derived uses undefined class Derived.

我怎样才能做这样的事情?

谢谢

最佳答案

要能够使用 Derived 类并调用其中的成员函数(包括构造函数和析构函数),完整 定义需要可用。在这种情况下,它不在 Base::func 函数中。

解决方案很简单:不要内联定义func,只需声明它,然后在定义Derived 类之后实现(定义)它。

关于C++如何创建创建派生类对象的基类,并访问基类的私有(private)成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45037379/

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