Bri*_*ian 8 c++ static pointers class
我还不太了解指针和引用,但是我有一个带有静态方法和变量的类,它们将从main类和其他类引用.我有一个在main()中定义的变量,我想通过静态函数传递给这个类中的变量.我希望这些函数更改main()范围中看到的变量的值.
这是我想要做的一个例子,但是我得到编译错误......
class foo
{
public:
static int *myPtr;
bool somfunction() {
*myPtr = 1;
return true;
}
};
int main()
{
int flag = 0;
foo::myPtr = &flag;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Naw*_*waz 20
在类外提供静态变量的定义:
//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
Run Code Online (Sandbox Code Playgroud)
除此之外,您还忘记了上面注释中指示的分号,并且somefunction需要返回一个bool值.