1、先看下一个类
Test.h
1 #define PI 3.14159 2 const int NUM = 3;//定义常量 3 class Test 4 { 5 public: 6 Test(); 7 virtual ~Test(); 8 virtual void action(const int input);//保护,防止意外修改 9 int getstate() const; 10 const MyClass istate(); 11 private: 12 static int mLay; 13 int mOut; 14 15 };
Test.cpp
1 #include <iostream> 2 #include "Test.h" 3 4 using namespace std; 5 6 Test::Test():mOut(1) 7 { 8 } 9 Test::~Test() 10 { 11 } 12 void Test::action(const int input) 13 { 14 input++; 15 } 16 17 int Test::getstate() const 18 { 19 return (mOut); 20 } 21 const int Test::istate() 22 { 23 mOut++; 24 return (mOut); 25 }
consttest.cpp
1 // consttest.cpp : 定义控制台应用程序的入口点。 2 // 3 4 #include "stdafx.h" 5 #include "Test.h" 6 7 int _tmain(int argc, _TCHAR* argv[]) 8 { 9 Test test; 10 int mFi = 9; 11 test.action(mFi); 12 return 0; 13 }
2、(1)以上程序编译,consttest.cpp---11行 会报错,因为不能给常量赋值。
(2)const定义常量从汇编的角度来看,只是给出了对应的内存地址,而不是象#define一样给出的是立即数,所以,const定义的常量在程序运行过程中只有一份拷贝,而#define定义的常量在内存中有若干个拷贝。因此使用const来定义常量比宏定义更能提高效率。
总结const作用有以下:
(1)定义常量;(2)保护,防止意外修改;(3)节省空间,避免不必要的内存分配;
3、int getstate() const与const MyClass istate() 区别;
int getstate() const:这里的const表明与客户代码的一个合约,即保证你不会在此方法中尝试修改对象的内部值,如果修改编译器将会报错,如例子1所示。
const MyClass istate() :这里的const表明,函数返回值型不可以被改变,函数返回什么类型,就要赋给什么类型。
例子1 Test.cpp
1 #include <iostream> 2 #include "Test.h" 3 4 using namespace std; 5 6 Test::Test():mOut(1) 7 { 8 } 9 Test::~Test() 10 { 11 } 12 void Test::action(const int input) 13 { 14 15 } 16 17 int Test::getstate() const 18 { 19 mOut++;//此句修改内部值,将报错 20 return (mOut); 21 } 22 const int Test::istate() 23 { 24 mOut++; 25 return (mOut); 26 }