浅析C++中的static(一些补充)

博客《浅析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;
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一苇渡江694

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值