C++のstaticを浅く分析する(いくつかの補足)

5997 ワード

ブログ『浅析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;
}