[英]Global variable in C++
I'm writing c++ project, which contains several classes. 我正在写c ++项目,其中包含几个类。 I created .h file named Position.h, with one array and one function: 我用一个数组和一个函数创建了名为Position.h的.h文件:
class Position
{
public:
Coord positions[25];
public:
void setPos(int index, double x, double y)
{
positions[index].x = x;
positions[index].y = y;
}
};
I want to set values in this array from another classes, so every class in this project will see the same values. 我想从另一个类在此数组中设置值,因此该项目中的每个类都将看到相同的值。 I included "Position.h" in other classes, but i can't access the "positions" array. 我在其他类中包括了“ Position.h”,但无法访问“ positions”数组。
Anyone can help me plz?? 有人可以帮助我吗?
positions
is a member variable associated with a class instance, and therefore not a global. positions
是与类实例关联的成员变量,因此不是全局变量。 You can make it similar to a global by making it static
. 您可以通过使其变为static
使其类似于全局。 Doing so, it will become a class-scoped variable, and not bound to an instance. 这样做,它将成为一个类作用域变量,而不是绑定到实例。
You will need to define it in a single implementation file. 您将需要在单个实现文件中定义它。
An even better alternative would be having an std::vector<Coord>
. 更好的选择是使用std::vector<Coord>
。
Just chnage the statement : 只是更改语句:
Coord positions[25];
to 至
static Coord positions[25];
also change void setPos
to 也将void setPos
更改为
static void setPos
while accesing the array ,access it as: 访问数组时,按以下方式访问它:
Position::positions[any value]
But before accessing the array,make sure you call the function setPos
但是在访问数组之前,请确保调用函数setPos
As suggested by others, you can make the members static
. 如其他人所建议,您可以使成员成为static
。
You can also create an instance of the Position
class as a global variable, and use that: 您还可以将Position
类的实例创建为全局变量,并使用该实例:
Position globalPosition;
void function_using_position()
{
globalPosition.setPos(0, 1, 2);
}
int main()
{
function_using_position();
}
Or make it a local variable, and pass it around as a reference: 或将其设为局部变量,并将其作为参考传递:
void function_using_position(Position &position)
{
position.setPos(0, 1, 2);
}
int main()
{
Position localPosition;
function_using_position(localPosition);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.