错误:对classname :: member_variable

时间:2018-03-10 08:27:31

标签: c++ static-members

不能打印static int variable

的值

我想在此上下文中检查静态变量的值。

我使用www.codechef.com/ide作为IDE:C ++ 14(Gcc 6.3)作为语言+编译器。

CODE:

#include <iostream>
using namespace std;

class Demo_StaticVar
{
    public :
    static int a;

    Demo_StaticVar()
    {
      cout<<a<<endl;
    }

};

int main()
{
  Demo_StaticVar obj1;



  return 0;
}

ERROR:

  

/home/ptnn1S/ccl6RBkR.o:在函数`main&#39;:

     

prog.cpp :(。text.startup + 0xf):对Demo_StaticVar :: a&#39;的未定义引用    collect2:错误:ld返回1退出状态

截图:

enter image description here

2 个答案:

答案 0 :(得分:0)

static int a;

声明静态变量。这告诉编译器该字段存在且类型为int。这是编译代码的有用信息。

但变量仍然需要定义。这是一些翻译单元(恰好一个翻译单元)需要为这个变量分配内存。见What is a "translation unit" in C++

对于声明和定义的其他NIT,请检查此问题:What is the difference between a definition and a declaration?

至于解决方案,您还需要在课外添加定义:

int Demo_StaticVar::a;
int main(){
... 

代码链接:https://ideone.com/l7ie7p

答案 1 :(得分:0)

摘录: 当数据成员声明为静态时,只为该类的所有对象维护一个数据副本。

静态数据成员不是给定类类型的对象的一部分。因此,静态数据成员的声明不被视为定义。

来源:https://msdn.microsoft.com/en-us/library/b1b5y48f.aspx

相关问题