[英](C++) Invalid value when accessing variable from another class
Whenever I try to access time_series_length
from the Example
class I get an invalid number.每当我尝试从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;
}
I should get output我应该得到输出
30
30
,instead I get ,而不是我得到
30
-349926832
You did not assign anyting to the created instance of the Example object a
.您没有为 Example 对象a
的创建实例分配任何a
。 It was only initialized.它只是被初始化。 It dedicated a piece of memory to your class, but did not put anything in there, it's a random value in memory.它为你的班级分配了一块内存,但没有在里面放任何东西,它是内存中的一个随机值。
Initialization is missing for the Indicator class, which is part of "Example a;" Indicator 类缺少初始化,它是“示例 a”的一部分; You have to call Indicator initialization with object -> a;您必须使用 object -> a; 调用指标初始化; so you call respective method -> get_ts_length() instead data member as good coding practice.所以你调用各自的方法 -> get_ts_length() 而不是数据成员作为良好的编码实践。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.