且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何访问类的静态成员?

更新时间:2023-02-15 18:38:53

你声明静态成员很好,但不是在任何地方定义



基本上've说有一些静态成员,但从来没有为它留出一些内存,你需要:

  int A: :x = 100; 

在类别之外和 b $ b

I am starting to learn C++ and Qt, but sometimes the simplest code that I paste from a book results in errors.

I'm using g++4.4.2 on Ubuntu 10.04 with QtCreator IDE. Is there a difference between the g++ compiler syntax and other compilers? For example when I try to access static members something always goes wrong.

#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;
}

I think it's exactly the same as declared here and here (isn't it?). So what's wrong with the above code?

You've declared the static members fine, but not defined them anywhere.

Basically what you've said "there exists some static member", but never set aside some memory for it, you need:

int A::x = 100;

Somewhere outside the class and not inside main.