C++/Classes/Static Variable
Hi Everyone!
Topic:
I have a quick question regarding static variables in classes.
Background:
I'm creating a simple 2D brick breaker game. The Bricks are all the same texture and therefore have the same pixel information. In my Brick Class I have an array of Boolean values that hold if a pixel at x,y on the image is transparent.
Question:
Instead of having to extract all the information (transparent pixel or not) for every brick I would like to only have to do it once. I was wondering if it was possible to make the array static so if it changes in one instance of a brick it changes in all. Thus, I would only have to get the data once.
Other Possible Solutions:
1. My current solution is for every brick I get the pixel information from the texture.
2. Have the array outside of the class - I'd like it to be contained within the class if that's possible.
Code:
The way my code is organized is there is a GameObject class that has a p_PixelDataArray[x][y] . I would like to override this in the Brick class to be something like static p_PixelDataArray.
GameObject
bool** p_PixelDataArray
Brick : GameObject
static bool** p_PixelDataArray
Conclusion:
I'm not sure if this is correct use of static, or if I'm thinking about it wrong. I'm open for suggestions please!
Thank you,
-MsWho.
Here's a working example using a private static class member.
#include <iostream>using namespace std;#define WIDTH 4#define HEIGHT 4class GameObject{ public: void ModPixelDataArray (int x, int y, bool state) { p_PixelDataArray[x][y] = state; } void OutputPixelDataArray (void) { for (int y = 0; y < HEIGHT; y++) { for (int x = 0; x < WIDTH; x++) { cout << p_PixelDataArray[x][y]; } cout << endl; } } private: // Can only be modified from within GameObject static bool p_PixelDataArray[WIDTH][HEIGHT];};// Static members have to be contained outside the classbool GameObject::p_PixelDataArray[WIDTH][HEIGHT];int main (void){ // Create object GameObject go; // Modify the bool matrix go.ModPixelDataArray(2, 2, true); // Display matrix go.OutputPixelDataArray(); // Create object and display GameObject go2; go2.OutputPixelDataArray(); // Pause cin.get();}
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement