静态方法中的正常局部变量和静态局部变量之间有什么区别吗?
Is there any difference between normal and static local variables in static methods?
class A
{
static void f(void)
{
int a;
static int b;
}
};
a
和b
之间是否有任何(形式或实际)区别?
是的,请考虑以下事项:
#include <iostream>
using namespace std;
class A
{
public:
static void func()
{
static int a = 10;
int b = 10;
a++;
b++;
std::cout << a << " " << b << endl;
}
};
int main() {
A a, b;
a.func();
b.func();
a.func();
return 0;
}
a
在 func
的所有实例之间共享,但b
是每个实例的本地,因此输出为:
11 11
12 11
13 11
http://ideone.com/kwlra3
是的,两者都是不同的。对于每个调用,将创建a
,而b
将只创建一次,并且对于类型为 A
的所有对象都是相同的。同样,我的意思是,所有对象共享一个b
内存。
相关文章:
- 使用的未初始化局部变量'Quick'
- 修复未初始化的局部变量错误
- 局部变量保留函数中的值
- 如何使用 C++ 中的继承函数访问派生类中的局部变量
- 将引用分配给局部变量,如果局部变量超出范围,它会超出范围吗?
- Gnuplot_i.hpp C++接口绘制局部变量而不是文件
- 如何在函数外部访问函数中局部变量的值?
- 赋予全局变量而不是局部变量优先级的函数 - (异常行为)
- C++中静态方法的局部变量范围
- 未初始化的局部变量错误甚至认为我初始化了它(C++)
- 将共享指针传递给函数参数 - 将其分配给局部变量的正确方法是什么
- C++标准对局部变量的存储和分配有什么保证?
- 如果在静态局部变量之前出现异常,会发生什么
- 在函数中破坏局部变量是什么意思
- 静态方法中的正常局部变量和静态局部变量之间有什么区别吗?
- C++:全局变量与局部变量.使用什么
- 在c++中,通常在什么时候为局部变量分配内存?
- C++,静态局部变量(方法)与全局(文件)变量有什么区别
- C++中返回局部变量的引用和标准指针的替代方案是什么
- 能够在lambda中使用未捕获的局部变量的编译时特征有什么意义?