【发布时间】: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