Reputation: 193
e.g:
int main()
{
class exampleClass{
public:
int x;
};
exampleClass one;
exampleClass two;
exampleClass three;
if (exampleClass manipulate_all x == 5)
{
// do something
}
return 0;
}
}
instead of:
int main()
{
class exampleClass{
public:
int x;
};
exampleClass one;
exampleClass two;
exampleClass three;
if (one.x == 5)||(two.x == 5)||(three.x == 5)
{
// do something
}
return 0;
}
Very new to c++, so apologies if this is a stupid question, or if this is far too advanced for a beginner.
I'm trying to create a collision system for my game, where each sprite has a class object, so I can check the player object against every other sprite. If this is a terrible idea please tell me.
Upvotes: 0
Views: 103
Reputation: 337
If you want to have all members share a variable, you can use static variables
If they're part of a collision system you probably need a larger structure to hold all of the variables and just use a loop over that.
Alternatively, you could have a static variable as a list keep track of all other members of the class and loop over this, where the static variable is a vector of pointers to instantiated objects. This requires a lot more overhead for the individual class and its own function to modify all of the values.
Either way you'd have to write the container to hold all the values, but it's up to you on how you want to design it.
Modifying your class:
class exampleClass{
private:
static vector<exampleClass*> instances;
public:
exampleClass(){ instances.push_back(this);}
~exampleClass(){ /*Use some kind of id to find and erase the current instance from the list here.*/}
int x;
};
Upvotes: 2
Reputation: 18
You can, if your member is a static member, but not if it's an instance member, like your case. But you also need to initialize a static member outside the class.
#include<iostream>
class exampleClass
{
public:
static int x;
};
int exampleClass::x = 0;
int main()
{
exampleClass one;
exampleClass two;
exampleClass three;
exampleClass::x = 5;
std::cout << one.x << two.x << three.x << std::endl;
return 0;
}
Upvotes: 0