问题描述
我开始学习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.
这篇关于如何访问类的静态成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!