【问题标题】:How can I access a static variable from another method?如何从其他方法访问静态变量?
【发布时间】:2014-09-09 14:03:24
【问题描述】:

是否可以从foo2() 访问变量myVar

struct A {
    void foo() {
        static int myVar;
    }

    void foo2() {
        // can I access A::foo::myVar from here ??
    }
};

谢谢!

马西莫

【问题讨论】:

  • 你真正想做什么?
  • 它是,返回一个指针/引用它(就像一些 C 函数一样)但是你在 C++ 中,那么你应该认真考虑是否不应该将它更改为私有类字段.. .

标签: c++ variables static


【解决方案1】:

您可以从函数中返回对它的引用:

int& foo() {
    static int myVar;
    return myVar;
}

void foo2() {
    std::cout << foo() << std::endl;
}

请注意,您的问题并不清楚为什么您需要访问此变量。无论您要解决什么问题,都可能有更好的解决方案。

【讨论】:

    【解决方案2】:

    不,myVar 只是foo() 中的有效符号。如果您想从其他函数访问它,请将其提升到类中,就像这样。

    struct A {
        static int myVar;
    
        void foo() {
            A::myVar;
        }
    
        void foo2() {
            A::myVar;
        }
    };
    

    【讨论】:

      【解决方案3】:

      不,你不能在另一个函数中访问myVar变量。如果你把myVar作为结构数据成员会更好。

      struct A {
          static int myVar;
      
          void foo() {
      
          }
      
          void foo2() {
      
          }
      };
      

      【讨论】:

        【解决方案4】:

        您不能访问在其他方法体中声明的局部变量。所以答案是否定的,把变量 global 放到类中,你就可以访问了

        【讨论】:

          猜你喜欢
          • 2022-06-25
          • 2015-07-22
          • 2012-06-29
          • 2012-08-20
          • 1970-01-01
          • 2013-11-28
          • 1970-01-01
          • 1970-01-01
          • 2015-02-18
          相关资源
          最近更新 更多