-
Global declaration?
If I define my own class in a header file as follows:
Code:
class tug{
public:
int arraypos[3];
//other data members
} usertug,cputug;
Are usertug and cputug effectively global variables and can i access usertug.arraypos[(subscript)] from anywhere in my header file and in my source file? (provided obviously that i #include my header in the source)
-
-
I don't believe so. You have to define a variable as your class and make sure it is above everything and not in a function.
-
try this ...
try using a pointer or reference, it might work out for you !
-
The answer is yes. If you declare a variable in a header file (outside of functions etc..) it will be global throughout the program. but if you want to use it in all your header files put the declaration before you #include em.
-
Thanks for your help guys. I have found though that it isn't whether it is possible to access the variables that is the problem. I have never had an explanation for the problem and if anyone could explain or even better point me to a tutorial that does explain it, that would be great. OK, basically I have some classes for my battleships game, one for each type of ship. They are some thing like this:
Code:
class tug{
int nopos 2; //number of map positions it uses
int arraypos[2]; //integer values of grid positions
//other data members
}usertug, cputug;
class sub{
int nopos 3; //number of map positions it uses
int arraypos[3]; //integer values of grid positions
//other data members
}usersub, cpusub;
//etc....
I then created a template function for ship placement so that I could pass any of my ships into it to be positioned on the grid.
The function was:
Code:
template <class T>
T placeship(T aship....etc..)
{
//code to place ship
}
However, within the template function, I found that although when I used for example aship.nopos, and passed in usersub, the value was correctly 3. But when I tried to for example write aship.arraypos[0]=value, the value was never put into the array.
Any help on this topic would be gratefully received as I have not found it in any tutorials and it has not been taught to us at university.