C++ 常函數長函數
阿新 • • 發佈:2017-05-07
c++ 常函數
常函數的意義對與普通函數來說,因為const關鍵字的增加,體現在對類成員的保護上,現在加以講解:
#include <iostream> using namespace std; class Ctest { private: int a; public: Ctest( int a = 2) { this->a = a; } int doubleA() const { return a*2; } }; int main() { Ctest * cts = new Ctest(2); cout << cts->doubleA() << endl; delete cts; return 0; }
結果:
常函數->
int doubleA() const 就是在函數後加const
需要註意的是 :
①:構造函數和析構函數不可以是常函數
②:常函數不能對class的類成員進行修改(只能調用)如下面是不可以的:
但是可以對本函數內部聲明的參數進行修改
③:常函數的this指針,有別於普通函數的this指針
#include <iostream> using namespace std; class Ctest { private: int a; public: Ctest( int a = 2) { this->a = a; } int doubleA() const { return a*2; } const Ctest* my() const { return this; } Ctest* my1() { return this; } }; int main() { /*Ctest * cts = new Ctest(2); cout << cts->doubleA() << endl; delete cts;*/ Ctest cts(3); cout << cts.my()->doubleA() << endl; return 0; }
這裏有個註意點:常對象只能調用常對象,如下面是不允許的:
另外 :
#include <iostream> using namespace std; class Ctest { private: int a; public: Ctest( int a = 2) { this->a = a; } int doubleB() { return a*2; } int doubleA() const { return a*2; } const Ctest* my() const { return this; } Ctest* my1() { return this; } }; int main() { /*Ctest * cts = new Ctest(2); cout << cts->doubleA() << endl; delete cts;*/ const Ctest cts(3); cout << cts.doubleA() << endl; return 0; }
用 const Ctest cts(3) 也是定義常對象
當然,下面的方案也行:
const Ctest * cts = new Ctest(3); cout << cts->doubleA() << endl;
總結 ,常函數具有保護類成員的作用。
本文出自 “Better_Power_Wisdom” 博客,請務必保留此出處http://aonaufly.blog.51cto.com/3554853/1922882
C++ 常函數長函數