Static variable inside of struct

Started by
5 comments, last by TWild 20 years, 9 months ago
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
---------------------My specs (because I always forget to post them)Intel P4 2.4 GHz640 MB system memoryRadeon 9700 PROWindows XPDirectX 9DirectX 8.1 SDK
Advertisement
It looks right, actually..

Can you please post your error message??

Pperhaps you forgot to actually DECLARE the varaible?

I.e.

int myStruct::counter = 0;



www.cppnow.com
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
---------------------My specs (because I always forget to post them)Intel P4 2.4 GHz640 MB system memoryRadeon 9700 PROWindows XPDirectX 9DirectX 8.1 SDK
Oh, and, I get and undefined reference to myStruct::counter.
---------------------My specs (because I always forget to post them)Intel P4 2.4 GHz640 MB system memoryRadeon 9700 PROWindows XPDirectX 9DirectX 8.1 SDK
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.
like this:

#include <iostream>// define the structstruct 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 easilymyStruct::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;};
daerid@gmail.com
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
---------------------My specs (because I always forget to post them)Intel P4 2.4 GHz640 MB system memoryRadeon 9700 PROWindows XPDirectX 9DirectX 8.1 SDK

This topic is closed to new replies.

Advertisement