我可以从外部访问函数内部的静态变量吗? [英] Can I access static variables inside a function from outside

查看:66
本文介绍了我可以从外部访问函数内部的静态变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C/C ++:我可以从外部访问函数内部的静态变量吗?例如:

C/C++: Can I access static variables inside a function from outside? For example:

#include <iostream>
using namespace std;

void f()
{
    static int count = 3;
    cout << count << endl;
}

int main(int argc, char** argv)
{
    f::count = 5;   // apparently this is an invalid syntax.
    f();

    return 0;
}

推荐答案

不,在C和C ++中都不能.

No, you can't, neither in C nor in C++.

如果要维护与函数关联的状态,请定义具有适当状态和成员函数的类.(在C ++中.您还用C标记了问题;相同的技术也有效,但您需要自己做所有基础工作.)

If you want to maintain state associated with a function, define a class with the appropriate state and a member function. (In C++. You've also tagged the question with C; the same technique works but you need to do all the groundwork yourself.)

尽管它们有其用途,但在大多数情况下,非常量静态局部变量不是一个好主意.它们使您的函数处于线程不安全状态,并且经常使它一次调用".

Although they have their uses, most of the time non-const static locals are a bad idea. They make your function thread-unsafe, and they often make it "call-once".

这篇关于我可以从外部访问函数内部的静态变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆