我开始学习C++和Qt,但有时我从书中粘贴的最简单的代码会导致错误。
我在带有QtCreator集成开发环境的Ubuntu10.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(); // error: : undefined reference to 'A::x'
return 0;
}我认为它与声明的here和here完全相同(不是吗?)。那么上面的代码有什么问题呢?
发布于 2018-06-29 05:53:44
您需要在类外部定义类的静态成员变量,因为静态成员变量需要声明和定义。
#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;
}发布于 2010-11-05 17:14:32
尝试:
#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;
}发布于 2015-04-21 06:43:38
试一下这个例子:
#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;
}https://stackoverflow.com/questions/4104544
复制相似问题