Archived

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

TWild

Static variable inside of struct

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
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