如何访问类的静态成员?

sor*_*h-r 23 c++ static

我开始学习C++和Qt,但有时我从书中粘贴的最简单的代码会导致错误.

我正在使用g++4.4.2带有QtCreator IDE的Ubuntu 10.04.g ++编译器语法和其他编译器之间有区别吗?例如,当我尝试访问静态成员时总会出错.

#include <iostream>
using namespace std;
class A
{
   public:
      static int x;
      static int getX() {return x;}
};
int main()
{
   int A::x = 100; // error: invalid use of qualified-name 'A::x'
   cout<<A::getX(); // error: : undefined reference to 'A::x'
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

我认为这与此处此处声明的完全相同(不是吗?).那么上面的代码有什么问题?

Fle*_*exo 41

你已经声明静态成员很好,但没有在任何地方定义它们.

基本上你所说的"存在一些静态成员",但从不为它留出一些记忆,你需要:

int A::x = 100;
Run Code Online (Sandbox Code Playgroud)

在课外的某个地方而不是主要的.


Pra*_*rav 9

第[9.4.2]节

静态数据成员

静态数据成员在其类定义中的声明不是定义,除了cv-qualified void之外可能是不完整的类型. 静态数据成员的定义应出现在包含成员类定义的命名空间范围内.在命名空间范围的定义中,静态数据成员的名称应使用::运算符通过其类名进行限定


Mar*_*ork 7

尝试:

#include <iostream>
using namespace std;
class A
{
   public:
      // This declares it.
      static int x;
      static int getX(){return x;}
};

// Now you need an create the object so
// This must be done in once source file (at file scope level)
int A::x = 100;


int main()
{
   A::x = 200;
   // Note no int here. You can modify it

   cout<<A::getX(); // Should work
   return 0;
}
Run Code Online (Sandbox Code Playgroud)


小智 7

您需要在类之外定义类的静态成员变量,因为静态成员变量需要声明和定义。

#include <iostream>
using namespace std;
class A
{
   public:
      static int x;
      static int getX() {return x;}
};

int A::x;         // STATIC MEMBER VARIABLE x DEFINITION

int main()
{
   A::x = 100;    // REMOVE int FROM HERE
   cout<<A::getX();
   return 0;
}
Run Code Online (Sandbox Code Playgroud)