【问题标题】:(C++) Invalid value when accessing variable from another class(C++) 从另一个类访问变量时值无效
【发布时间】:2020-03-25 18:47:47
【问题描述】:

每当我尝试从Example 类访问time_series_length 时,我都会得到一个无效号码。

class Indicator
{
public:
    Indicator(){};
    Indicator(std::vector<DayData> data, int days)  // days = 30 from the main function
    {
        time_series = data;
        time_series_length = days;
        std::cout << time_series_length << std::endl; // PRINTS OUT (30) in the console
    };

    // Returns the length in days of the time series
    int get_ts_length()
    {
        return time_series_length;
    }

    // Returns the time series in a vector of DatData structs
protected:
    int time_series_length;  // the length of the time_series in days
    std::vector<DayData> time_series;
};

class Example : public Indicator
{
public:
    Example(){};
    void check()
    {
        std::cout << Indicator::time_series_length;  // PRINTS OUT (-349926832) in the console
    }
};

struct DayData
{
    double adj_close;
    int volume;
};

int main()
{
    const int days = 30;

    // ... I populate data with DayData structs

    Indicator(data, days);

    Example a;
    a.check();
    return 0;
}

我应该得到输出

30
30

,而不是我得到

30
-349926832

【问题讨论】:

  • 请不要描述// days = 30 from the main function之类的代码。而是创建一个正确的minimal reproducible example。添加main,以便问题本身可以完整复制。
  • time_series_length 在哪里初始化? Indicator(){}; 不这样做。
  • 我们需要一个minimal reproducible example
  • 我在编辑中添加了main函数。谢谢。
  • Indicator(data, days); 创建一个超出范围的临时变量。 Example a; 创建一个新的独立变量,它与之前创建的临时变量没有任何关系。即使临时没有超出范围,您也有独立的对象。 a 从未初始化。

标签: c++ inheritance integer overflow


【解决方案1】:

您没有为创建的示例对象a 的实例分配任何内容。它只是被初始化。它为你的班级分配了一块内存,但没有放任何东西,它是内存中的随机值。

【讨论】:

    【解决方案2】:

    Initialization 类缺少初始化,它是“示例 a”的一部分; 您必须使用 object -> a 调用指标初始化;所以你调用相应的方法 -> get_ts_length() 而不是数据成员作为良好的编码习惯。

    【讨论】:

      猜你喜欢
      • 2014-09-30
      • 2021-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多