问题描述
有人可以解释静态方法变量如何在C ++中工作...如果我有以下类:
{
void foo(){
static int i;
i ++;
}
}
如果我声明多个A实例, ()在一个实例上增加所有实例上的静态变量i?
我假设每个实例都有自己的i的副本,但是通过一些代码,我似乎指出了其他情况。 / p>
因为 A类
解决方案
/ code>是一个非模板类,
A :: foo()
是一个非模板函数。
的任何实例只能在程序中使用 static int i
> A
对象将影响相同的 i
,并且 i
的生命周期将保留程序。添加示例:
A o1,o2,o3;
o1.foo(); // i = 1
o2.foo(); // i = 2
o3.foo(); // i = 3
o1.foo(); // i = 4
Can someone please explain how static method variables work in C++... if I have the following class:
class A {
void foo() {
static int i;
i++;
}
}
If I declare multiple instances of A, does calling foo() on one instance increment the static variable i on all instances? Or only the one it was called on?
I assumed that each instance would have its own copy of i, but stepping through some code I have seems to indicate otherwise.
Cheers
解决方案 Since class A
is a non-template class and A::foo()
is a non-template function. There will be only one copy of static int i
inside the program.
Any instance of A
object will affect the same i
and lifetime of i
will remain through out the program. To add an example:
A o1, o2, o3;
o1.foo(); // i = 1
o2.foo(); // i = 2
o3.foo(); // i = 3
o1.foo(); // i = 4
这篇关于类方法中的静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!