带有静态指针的 C++ 类

标签 c++ class pointers static

我还不是很了解指针和引用,但我有一个包含静态方法和变量的类,它们将从主类和其他类中引用。我在 main() 中定义了一个变量,我想将其传递给此类中具有静态函数的变量。我希望这些函数更改在 main() 范围内看到的变量的值。

这是我正在尝试做的一个例子,但是我遇到了编译器错误...

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 值。

关于带有静态指针的 C++ 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7033649/

相关文章:

c - Halcon/HDevelop 套接字发送通用图像数据

c - 为列表中的每个元素分配一个指针

java - 如何让 Class.forName 忽略小写/大写

c++ - 使用 shared_from_this 返回的指针访问私有(private)成员

c++ - 如何防止 strncpy_s 在调试版本中填充目标缓冲区?

c++ - 在另一个命名空间中使用外部 yyin

c++ - 虚拟方法不虚拟

python - "classes themselves are objects"是什么意思?

c++ - 在指针上重载 operator++

c++ - 如何调用父类类型列表的子类的方法? C++