C ++ class with static pointer

I do not understand pointers and references very well, but I have a class with static methods and variables that will be referenced by the main and other classes. I have a variable defined in main () that I want to pass to a variable in this class with static functions. I want these functions to change the value of a variable that is visible in the main () area.

This is an example of what I am trying to do, but I am getting compiler errors ...

class foo { public: static int *myPtr; bool somfunction() { *myPtr = 1; return true; } }; int main() { int flag = 0; foo::myPtr = &flag; return 0; } 
+8
c ++ pointers static class
source share
2 answers

Provide a definition of a static variable outside the class as follows:

 //foo.h class foo { public: static int *myPtr; //its just a declaration, not a definition! bool somfunction() { *myPtr = 1; //where is return statement? } }; //<------------- you also forgot the semicolon ///////////////////////////////////////////////////////////////// //foo.cpp #include "foo.h" //must include this! int *foo::myPtr; //its a definition 

In addition, you also forgot the semicolon, as indicated in the comment above, and somefunction should return a bool value.

+15
source share
 #include <iostream> using namespace std; class foo { public: static int *myPtr; bool somfunction() { *myPtr = 1; return true; } }; ////////////////////////////////////////////////// int* foo::myPtr=new int(5); //You forgot to initialize a static data member ////////////////////////////////////////////////// int main() { int flag = 0; foo::myPtr = &flag; return 0; } 
0
source share

All Articles