博客《浅析C++中的static》中讲述了一些关于static的用法,但是不够详细。现在进行一些补充。
1.static变量不能声明为mutable
class X {
public:
mutable static int fx1;//错误
void inc1()
{
}
};
int X::fx1=1;
2.局部类内不能有static成员变量
int main() {
class X{ //class X is a local class
static int fx1;
};
int X::fx1=1;
3.static成员函数不能返回void,也不能使用后缀const和volatile
class X{
public:
static void fx1() const; //this will give a error
X(){};
};
4.static成员变量可以如下进行初始化:
class X{
public:
static int f1;
static int f2;
static int f3;
static int f4;
static int f5;
static int f6;
int f7;
static int f(){return 100;}
X():f7(100){};
};
X x;
int X::f1=10;
int X::f2=X::f1; //using f1 to initialize f2
int X::f3=X::f();//initialized using static function
int X::f4=x.f1; //intialized with object data member
int X::f5=x.f(); //initialized with function from object
int X::f6=x.f7;//initialized using non static member of object
5.类不能具有static和非static同名的成员函数
class X{
public:
static int a;
static int inc()
{
a=a+1;
}
int inc() //this will give an error
{
}
X(){};
};
6.static成员函数不能有const、volatile修饰符
class X{
public:
int b;
static int a;
const volatile static int inc() //this is allowed
{
a=a+1;
}
X(){};
};
7.static成员函数不能被声明为虚函数
class X{
public:
int b;
static int a;
const volatile static int inc() //this is allowed
{
a=a+1;
}
X(){};
};
8.static成员函数只能对static成员变量和枚举进行操作
class X{
public:
int b;
static int a;
enum mode{a1,a2,a3};
static int inc()
{
return a1; //this is allowed since it is of enum type
}
X(){};
};
9.类中的静态成员具有外部链接性
X(){};
};
X x2;
int X::a=0;//static data member defined here
file : a2.cpp
class X{
public:
static int a;
static int inc();
};
X x1;
int b()
{
x1.a=100; //static data member is updated
return x1.a;
}