【问题标题】:cannot access private member declared in class while using protected and inheritance使用受保护和继承时无法访问在类中声明的私有成员
【发布时间】:2020-09-14 07:54:05
【问题描述】:

我在使用protected 成员时遇到了一些问题。相关代码和我得到的错误如下。这些类具有所有需要的函数和变量。我刚刚总结了相关部分。我该怎么办?

MFS.h:

class MFS
{
protected:
    MatrixXd commandedLateral;
};

CSimulator.h:

class CSimulator : MFS
{
};

CSimulator.cpp:

void CSimulator::calculateActuator(MFS* mfs)
{
    actuator = -gain * mfs->commandedLateral(1,0);
}

错误 C2248:“MFS::commandedLateral”:无法访问在“MFS”类中声明的私有成员

【问题讨论】:

    标签: c++ variables inheritance member protected


    【解决方案1】:

    protected成员只能通过派生类访问,即不能通过基类MFS访问。

    (强调我的)

    类的受保护成员只能访问

    1) 给该班级的成员和朋友;

    2) 任何派生类的成员and friends (until C++17) 那个类,但只有当通过它的对象的类 访问受保护的成员是该派生类或派生类 该派生类的

    例如下面的代码应该可以正常工作。

    void CSimulator::calculateActuator(CSimulator* mfs)
    {
        actuator = -gain * mfs->commandedLateral(1,0);
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-03
      • 2023-03-23
      • 2015-11-29
      • 2014-07-06
      • 1970-01-01
      • 1970-01-01
      • 2018-10-21
      相关资源
      最近更新 更多