访问一个成员类的指针,该成员类存储指向另一个成员类的指针

Accessing a pointer to a member class which stores a pointer to another member class

本文关键字:成员类 指针 存储 另一个 一个 访问      更新时间:2023-10-16

我有一个类指向数据存储成员类(Inputs):

class Calc
{
public:
    Calc(Inputs *input) : input(input) {}
    void performCalc();
private:
    Inputs *input;
};

在Inputs类中,我存储了各种数据输入:

class Inputs
{
public:
    Inputs(std::string &directory, LogFile &log);
    ~Inputs();
private:
    WriteLogFile &writeToLog;
    WeatherData *weather;
    EvaporationData *evaporation;
friend class Calc;
}

现在,当我在performCalc()方法中,我不能在输入对象中访问我的天气类,该对象是Calc类的成员,使用指针表法?

input->weather    //does not work

点表示法也不起作用(我不认为它会,因为这里没有通过引用传递的链接。)

input.weather    //does not work

我错过了什么?

编辑:

对不起!我忘了提到Calc类已经是Inputs类的一个friend class

您已经将weather定义为Inputs的私有成员,因此它对Calc对象不可见。您有3个选项:

  1. weather设置为public。
  2. CalcInputs好友
  3. weather创建一个getter方法(推荐,因为它改善了封装)

由于'Input'类的'weather'成员在私有字段中,您正试图从Calc类的'performCalc'方法访问,这是Input类之外。我认为这就是以上两种方法都行不通的原因。

将'weather'变量放入Input类的公共字段或尝试下面,使用get()方法访问Input类的私有字段

class Inputs
{    
public:
    Inputs(std::string &directory, LogFile &log);
    ~Inputs();
    WeatherData* getWeatherData(){
     return weather ;
    }
private:
    WriteLogFile &writeToLog;
    WeatherData *weather;
    EvaporationData *evaporation;
}