繁体   English   中英

How to access static class variable in static member function of same class?

[英]How to access static class variable in static member function of same class?

我提供我的样本:

  class a
  {
      public:
           static int m_n;
           static  int memfuc();
  };
  int a::memfuc()
  {
        int k =m_n;
         return k;
  }

但以下示例抛出 linker 错误:未解析的外部符号

您尚未定义(而不是声明)您的 static class 成员变量。

您可以将此代码放在某处的实现文件 (.cpp) 中:

int a::m_n = 123456;

您需要在某处提供实现:

int a::m_n;

对于 static,您必须将其定义为:

class a
{
    public:
       static int m_n;
       static  int memfuc();
};

int a::m_n = 0;

int main()
{
    a my_a;
}

my2c

您需要定义成员m_n ,但您还需要正确访问该成员。

您需要添加:

int a::m_n = 0  // Or some number of your choice

现在 m_n 已定义,您可以在任何地方访问它,而不仅仅是在其他成员函数中:

int get_m_n()
{
    int k = a::m_n;
    return k;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM