【问题标题】:C++ How to create base class which creates derived class object, and access private members of base class?C ++如何创建创建派生类对象的基类,并访问基类的私有成员?
【发布时间】:2017-12-15 16:24:01
【问题描述】:

有什么方法可以让derived class 访问base classprivate 成员,同时能够在@ 内的base class 方法上创建derived 对象987654326@?

类似这样的:

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.

我该怎么做?

谢谢

【问题讨论】:

  • public: int mBase = 5;,根据您的问题,您可能是指private。事实上,您可能希望 protected 允许继承的类访问它。

标签: c++ inheritance derived-class base-class


【解决方案1】:

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

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

【讨论】:

  • ...如果您在标题中定义它,请不要忘记inline :)
【解决方案2】:

访问基类私有成员的派生类

通常只写protected 而不是private。有什么理由你不能这样做吗?

Error: derived uses undefined class Derived.

在基类定义中声明func,并在派生类定义后定义

class Base {
public:
    void func();
protected:
    int mBase = 5;
};

class Derived : public Base {
public:
    void func() {
        mBase = 6; 
    }
};

void Base::func() {
    Derived derived;
    derived.func();
}

【讨论】:

    【解决方案3】:

    您应该阅读多态性。您可能想要的是使 func() 虚拟:

    class Base
    {
    public:
        virtual void func() { /* Base behavior */ } // or pure = 0
        virtual ~Base() = default; // don't forget!
    public:
        int mBase = 5;
    };
    
    class Derived : public Base
    {
    public:
        void func() override
        {
            // Derived behavior
        }
    };
    

    关于访问Base::mBase,您有两种选择:

    • 使mBase受保护
    • 添加您在 Derived 中使用的受保护设置器来修改它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-10
      • 1970-01-01
      • 2017-08-07
      • 2011-07-20
      • 2020-03-17
      • 2020-08-06
      • 2017-01-16
      相关资源
      最近更新 更多