静态变量内部成员函数的基类 [英] static variable inside member function of base class

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

问题描述

我有以下内容:

  class base 
{
public
void f ();
...
}
void base :: f()
{
static bool indicator = false;
.....
if(!indicator)
{
...
indicator = true;
}
}
class D:public base
{
...
}


  main 
{
// D
base的第一个实例* d1 = new D();
d1-> f();
....
// D
base的第二个实例* d2 = new D();
d2-> f();
}



我发现第一次实例化D并调用d1-> f )静态变量设置为false。但第二次我调用d2-> f()的代码甚至没有命中行static bool indicator = false;并保持为true(从第一遍d1-f())这正是我想要的行为,但我不明白为什么会发生这种情况。可以有人请解释发生了什么。提前感谢

解决方案

成员函数中声明的静态变量将在函数调用之间保持其值。在所有实例上只有一个副本,并且来自不同实例的对指示符的所有访问将影响相同的 / code>。这意味着指标 只会初始化一次



类方法中的静态变量



此代码不切换指示符,它总是设置为true如果它是false(我确定是你想要的行为)。

  if(!indicator)
{
...
indicator = true;
}


i have the following:

   class base
   {
      public
       void f();
       ...
   }
    void base::f()
    {
        static bool indicator=false;
         .....
         if(!indicator)
         {
            ...
            indicator=true;
          }
     }
    class D:public base
    {      
       ...
     }

in my main() i have:

      main()
      {
          // first instance of D
          base *d1 = new D();
          d1->f();
           ....
           // 2nd instance of D
          base *d2 = new D();
          d2->f();
       }

i find that the first time i instantiate D and call d1->f() the static variable is set to false. but the 2nd time i call d2->f() the code does not even hit the line "static bool indicator=false;" and it is kept at true (from the first pass of d1-f()) This is exactly the behavior i want but i do not understand why this is happening. can someone please explain what is happening. thanks in advance

解决方案

Static variables declared in member functions will keep their value between function calls. There will be only one copy over all instances, and all accesses to indicator from different instances will affect the same indicator. This means indicator will only be initialized once.

See here for more info: Static variables in class methods

Also this code does not toggle indicator, it always sets it to true if it's false (which I'm sure is the behaviour you want).

if(!indicator)
     {
        ...
        indicator=true;
      }

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

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