我开始学习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)
在课外的某个地方而不是主要的.
第[9.4.2]节
静态数据成员
静态数据成员在其类定义中的声明不是定义,除了cv-qualified void之外可能是不完整的类型. 静态数据成员的定义应出现在包含成员类定义的命名空间范围内.在命名空间范围的定义中,静态数据成员的名称应使用
::
运算符通过其类名进行限定
尝试:
#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)
归档时间: |
|
查看次数: |
55665 次 |
最近记录: |