Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

TWild

Static variable inside of struct

This topic is 5558 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I''m having problems referencing my static variable declared in my struct: say I have:

struct myStruct {
     int number;
     static int counter;
};

And I

myStruct *tmp;

tmp = new myStruct;
tmp->number = myStruct::counter;  // problem

myStruct::counter++;              // problem


I know the myStruct::counter is not right for referencing my struct... can anyone tell me how to do it? --------------------- My specs (because I always forget to post them) Intel P4 2.4 GHz 640 MB system memory Radeon 9700 PRO Windows XP DirectX 9 DirectX 8.1 SDK

Share this post


Link to post
Share on other sites
Advertisement
So, eventhough it is inside of the struct it is not being declared when I use new?

---------------------
My specs (because I always forget to post them)

Intel P4 2.4 GHz
640 MB system memory
Radeon 9700 PRO
Windows XP
DirectX 9
DirectX 8.1 SDK

Share this post


Link to post
Share on other sites
you need to have a definition of the variable in the myClass.cpp file (or whereever)

it''s like having a global variable that is declared in a header as extern but needs defining once, somewhere in a cpp file.

Share this post


Link to post
Share on other sites
like this:


#include <iostream>


// define the struct

struct myStruct
{
myStruct();
int i;
// this declares the static variable

// no storage is allocated for it yet

static int counter;
};

// this actually defines it, and makes it exist

// (storage for the variable in created in the

// executable) Should go in a .cpp file (_not_ .h)

int myStruct::counter = 0;

// now, in other code you should be able to access it easily

myStruct::myStruct()
{
i = ++counter;
}

int main(int argc,char** argv)
{
using namespace std;
myStruct* v1 = new myStruct();
myStruct* v2 = new myStruct();
myStruct* v3 = new myStruct();

cout << v1->i << endl;
cout << v2->i << endl;
cout << v3->i << endl;

delete v1;
delete v2;
delete v3;
return 0;
};

Share this post


Link to post
Share on other sites
Got it, thanks guys!

---------------------
My specs (because I always forget to post them)

Intel P4 2.4 GHz
640 MB system memory
Radeon 9700 PRO
Windows XP
DirectX 9
DirectX 8.1 SDK

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!