C++:如何从静态函数写入全局变量

C++: How to write from a static function to a global variable

本文关键字:全局变量 静态函数 C++      更新时间:2023-10-16

我想访问一个变量(通过ctypes),它应该是静态void函数的结果,即监听广播。

那么,除了使用 "return" 语句之外,我如何从静态函数中获取信息呢?

编辑:

这是我的意思的示例代码:

class Foo{
int bar;
static void listener(){
bar = 3;
}
main(){
    listener();
    }
}

静态方法只能访问静态成员:

class Foo {
    static int bar;
public:
    static void listener() { bar = 3; }
};
int Foo::bar = 0;
int main()
{
    Foo::listener();
}

您可以将变量声明为 static

class Foo {
public:
   static int bar;
   static void listener() {
       bar = 3;
   }
};

int Foo::bar = 0;
main() {
    Foo::listener();
    }
    // now use Foo::bar. It's value is 3.
}

请注意,正在publicstatic的变量可以由每个人修改,而不仅仅是通过Foo::listener