C++笔记------static 和 const 在类中用法

static:

  由关键字static修饰说明的类成员,成为静态类成员。类的静态成员为其所有对象共享,不管有多少对象,静态成员只有一份存于公用内存中。
  初始化在类外,由类名做限定初始化,不能再构造函数中初始化。

class Test
{
private:
    static int count;
    int num;
public:
    Test(int b=0):num(b){
        count++;
    }
    ~Test(){
        count--;
    }
}; 
//类外用类名做限定进行初始化
int Test::count = 0;

  可以通过类名访问静态类成员变量,也可以使用对象名访问

//mm是类的友元函数
void
mm(const Test & t) { cout << t.num << endl; cout << Test::count << endl; cout << t.count <<endl; }


  静态成员函数只能访问静态变量,原因是静态方法没有this指针,不能访问普通成员 。
  一般成员函数访问普通成员是有this指向,默认有this指针。

    void Show()    //相当于 void Show(const Test * this)
    {
        cout << num <<endl; //想当于 cout << this->num <<endl;
        cout << count << endl;
    }
    //相当于static void show1 ()
    static void Show1()
    {
        //cout << num <<endl;  
        cout << count <<endl;
    }

  静态成员函数只能调用静态成员函数,但一般成员函数能调用静态成员函数。

    void Show()
    {
        cout << num <<endl;
        Show1();
    }
    static void Show1()
    {
        //cout << num <<endl;  
        cout << count <<endl;
        //Show(); //出现 cannot call member function 'void Test::Show()' without object的错误
    }
    static void Show()
    {
        cout << "fffff" <<endl;
        //Show1();
    }
    //static void show1 ()
    static void Show1()  //因为都是static 所以不会出现问题
    {
        //cout << num <<endl;  
        cout << count <<endl; 
        Show();
    }
  void list() //普通成员方法
  //void list() ==> void list ( Test * const this) this指向的是常量
  void list() const //常方法
  //void list() ==>void list ( const Test * const this) this是常量

  常方法 不能在方法内部进行数据修改

  一般方法可以调用常方法。常方法不能调用一般方法。

出现这些问题都是因为this指针。static修饰的类成员没有this指针,const修饰的类成员函数位置不同,效果不同。

原文地址:https://www.cnblogs.com/zhangzeze/p/8710942.html