如何访问类的静态成员? [英] How to access static members of a class?

查看:128
本文介绍了如何访问类的静态成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我在使用QtCreator IDE的Ubuntu 10.04上使用 g ++ 4.4.2 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(); //错误::未定义引用'A :: x'
return 0;
}



我认为它与声明在这里在这里(isn' t it?)。

解决方案

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



基本上'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.

这篇关于如何访问类的静态成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆