首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何访问类的静态成员?

如何访问类的静态成员?
EN

Stack Overflow用户
提问于 2010-11-05 17:04:06
回答 4查看 66.8K关注 0票数 32

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

我在带有QtCreator集成开发环境的Ubuntu10.04上使用g++4.4.2。g++编译器的语法和其他编译器有什么区别吗?例如,当我试图访问静态成员时,总会出错。

代码语言:javascript
复制
#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;
}

我认为它与声明的herehere完全相同(不是吗?)。那么上面的代码有什么问题呢?

EN

回答 4

Stack Overflow用户

发布于 2018-06-29 05:53:44

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

代码语言:javascript
复制
#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;
}
票数 8
EN

Stack Overflow用户

发布于 2010-11-05 17:14:32

尝试:

代码语言:javascript
复制
#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;
}
票数 7
EN

Stack Overflow用户

发布于 2015-04-21 06:43:38

试一下这个例子:

代码语言:javascript
复制
#include<iostream>
using namespace std;

class check
{
        static int a;
    public:
        void change();
} ;
int check::a=10;
void check::change()
{
    a++;
    cout<<a<<"\n";
}

int main()
{

    int i,j;
    check c;
    check b;
    c.change();
    b.change();
    return 0;
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4104544

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档