学习c++中static 的用法如下:
Static member functions in C++ are the functions that can access only the static data members. These static data members share a single copy of themselves with the different objects of the same class.
写了下面的代码进行一个小测试。
# include <iostream>
using namespace std;
// test static in class
class TestStatic {
public:
static int a;
int b;
TestStatic() {
b = 0;
a = 6;
}
static void print() {
cout << a << endl;
}
static void set(int b) {
a = b;
}
};
int main() {
TestStatic a ;
TestStatic b ;
a.print();
b.print();
a.set(10);
a.print();
b.print();
return 0;
}
发现编译时出现错误:
undefined reference to `TestStatic::a';
collect2: ld returned 1 exit status
原来这是因为static变量没有初始化。由于不能直接在类定义时进行初始化,可以在类定义后进行初始化赋值,修改后如下:
# include <iostream>
using namespace std;
// test static in class
class TestStatic {
public:
static int a;
int b;
TestStatic() {
b = 0;
a = 6;
}
static void print() {
cout << a << endl;
}
static void set(int b) {
a = b;
}
};
int TestStatic::a = 5;
// this line is used to initialize the static variable
int main() {
TestStatic a ;
TestStatic b ;
a.print();
b.print();
a.set(10);
a.print();
b.print();
return 0;
}
程序能够正常编译运行: