问题描述
我不太理解指针和引用,但我有一个类,静态方法和变量,将引用从主和其他类。我有一个变量定义在main(),我想传递给这个类中的一个变量与静态函数。我想让这些函数改变在main()范围内看到的变量的值。
I don't understand pointers and references very well yet, but I have a class with static methods and variables that will be referenced from 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 those functions to change the value of the variable that is seen in the main() scope.
这是我想做的一个例子,但我获取编译器错误...
This is an example of what I am trying to do, but I get compiler errors...
class foo
{
public:
static int *myPtr;
bool somfunction() {
*myPtr = 1;
return true;
}
};
int main()
{
int flag = 0;
foo::myPtr = &flag;
return 0;
}
推荐答案
类外的变量:
//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
除此之外,您还忘记了上面注释中指出的分号, somefunction
需要返回 bool
值。
Beside that, you also forgot the semicolon as indicated in the comment above, and somefunction
needs to return a bool
value.
这篇关于C ++类与静态指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!