gpt4 book ai didi

c++ - 使用 protected 和继承时无法访问在类中声明的私有(private)成员

转载 作者:行者123 更新时间:2023-12-02 10:15:38 26 4
gpt4 key购买 nike

我在使用 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”中声明的私有(private)成员

最佳答案

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

(强调我的)

A protected member of a class is only accessible

1) to the members and friends of that class;

2) to the members and friends (until C++17) of any derived class of that class, but only when the class of the object through which the protected member is accessed is that derived class or a derived class of that derived class:



例如下面的代码应该可以正常工作。
void CSimulator::calculateActuator(CSimulator* mfs)
{
actuator = -gain * mfs->commandedLateral(1,0);
}

关于c++ - 使用 protected 和继承时无法访问在类中声明的私有(private)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62040321/

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