C++ const相關問題 CV限定問題

 http://hi.baidu.com/monsterfairy/item/030b4be52951c22c5a2d6493
 
情況1:非成員函數不能有CV限定,即const,volatile限定關鍵字


情況2:靜態成員函數不能有CV限定,即const,volatile限定關鍵字

總結:只有非靜態成員函數纔可以使用const,volatile限定關鍵字


寫個Demo說明下

#include <iostream>
using namespace std;
  
class test {
public:
    test(){};
    virtual ~test(){};
  
    /*static*/ void showMe() const { //加上static,會報 成員函數‘static void test::showMe()’不能擁有 cv 限定符
        cout<<"show me is ok!"<<endl;
    }
  
    static void showHe() {
        cout<<"show he is ok!"<<endl;
    }
  
    void showYou() {
        cout<<"show you is ok!"<<endl;
    }
};
  
  
/*static*/ void tt() /*const*/{ //加上const 會報錯誤:非成員函數‘void tt()’不能擁有 cv 限定符,無論是否是靜態
    cout<<"tt2 show tt is ok!"<<endl;
}
  
int main(void) {
    const test t;  //加上const限定,會影響類的非const返回方法 t.showYou()會報錯
    t.showHe(); //靜態方法不受const類限制
    t.showMe();
   //    t.showYou(); //會報丟棄了類型限定,const類,只能調用const限定函數
    tt();
    return 0;
} 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章