Thierry Mathieu
July 19th, 1999, 09:03 AM
hello, i made an int variable named "My_var"
i want to acces to it from all my classes, how can i do ?
i want to acces to it from all my classes, how can i do ?
|
Click to See Complete Forum and Search --> : Global variable Thierry Mathieu July 19th, 1999, 09:03 AM hello, i made an int variable named "My_var" i want to acces to it from all my classes, how can i do ? bimmer boy July 19th, 1999, 09:06 AM you'll need to extern it to every file that will use it: in file1.cpp int My_Var; if file2.cpp that will use My_Var extern int My_Var; miked Le Sant Yves July 19th, 1999, 09:08 AM Hi Make it global, i.e. declare it outside any class in a .h file or in a dedicated .h file. Place extern int MyVar in cpp file where you need this variable. Or place this statement in a dedicated .h file. You must only be sure that you DECLARE your variable once. HTH Yves Le Sant Metrology and Measurement Unit Fundamental and Experimental Aerodynamics Departement ONERA Meudon (Office National d'Etudes et de Recherches Aérospatiales) FRANCE John Killingbeck July 19th, 1999, 10:09 PM The extern keyword does not redefine the variable. It tells the compiler to look elsewhere for the variable declaration. One more item about global variables: if you have a local variable of the same name, then within that function calling that name will refer to the local variable. To access the global variable use the scope resolution operator ::. If you always use the scope resolution operator to access a global then you can easily identify globals in your code. In file pair MyClass1.cpp/MyClass1.h: int nMyInt; // global variable void MyFunction() { int nMyInt; // local variable nMyInt = 1; // assign 1 to local variable ::nMyInt = 2; // assign 2 to global variable } In file pair MyClass2.cpp/MyClass2.h: extern int nMyInt; Thierry Mathieu July 20th, 1999, 01:27 AM thank you all, it's a very good help codeguru.com
Copyright Internet.com Inc., All Rights Reserved. |