Reputation: 559
I'm writing c++ project, which contains several classes. I created .h file named Position.h, with one array and one function:
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.
Anyone can help me plz??
Upvotes: 0
Views: 437
Reputation: 409442
As suggested by others, you can make the members static
.
You can also create an instance of the Position
class as a global variable, and use that:
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);
}
Upvotes: 1
Reputation: 67291
Just chnage the statement :
Coord positions[25];
to
static Coord positions[25];
also change void setPos
to
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
Upvotes: 1
Reputation: 258648
positions
is a member variable associated with a class instance, and therefore not a global. You can make it similar to a global by making it 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>
.
Upvotes: 1