成员函数中的静态变量 [英] Static variables in member functions

查看:80
本文介绍了成员函数中的静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释一下成员函数中的静态变量如何在C ++中工作。

Can someone please explain how static variables in member functions work in C++.

给出以下类别:

class A {
   void foo() {
      static int i;
      i++;
   }
}

如果我声明了多个 A ,确实在一个实例上调用 foo()会增加静态变量 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 副本,但是单步执行某些代码似乎似乎表示相反。

I assumed that each instance would have its own copy of i, but stepping through some code I have seems to indicate otherwise.

推荐答案

由于 A类是非模板类, A :: foo()是非模板函数。程序内将只有一个 static int i 副本。

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.

任何 A 对象将影响相同的 i ,并且 i 的生存期将一直保留到整个程序。举个例子:

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

这篇关于成员函数中的静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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