C++ 常量成员常量返回值详解
总结: 2.常量成员函数,形式:type funname(type1 arg1,type2 arg2,...) const 3.返回常量的函数,可以是常量指针,指针常量,常量,形式: #include "stdafx.h" #include <iostream> using namespace std; class CTest { public: CTest(int nid,int nlimit):m_cntLimit(nlimit) { //m_cntLimit = nlimit;// 常量成员必须在构造函数列表在中给出 m_nId = nid; } ~CTest(){}; int GetID() const { //m_nId++;常量成员函数不能修改对象 //ClientGetObj();常量成员函数不能调用非常量成员函数 return m_nId; } CTest operator =(const CTest &b) { this->m_nId = b.m_nId; //this->m_cntLimit = b.m_cntLimit;// 常量数据成员不能拷贝 return (*this); } int ClientGetID() { return GetID(); } CTest* const GetObj() { return this; } CTest* ClientGetObj() { return this; } const int GetID() { return m_nId; } void Print() { cout<<"m_nId:"<<m_nId<<",const m_cntLimit"<<m_cntLimit<<endl; } void PrintCnt() const { cout<<"m_nId:"<<m_nId<<",const m_cntLimit"<<m_cntLimit<<endl; } private: int m_nId; const int m_cntLimit; }; void main() { CTest Obj1(1,1000); CTest Obj2(2,2000); CTest* pObj = Obj1.ClientGetObj(); pObj->Print(); CTest objTemp = *(Obj1.ClientGetObj()); *pObj = *(Obj2.ClientGetObj()); pObj->Print(); // reset *pObj = objTemp; cout<<"-------------const display---------------"<<endl; /*const */CTest* const pCntObj = Obj1.GetObj();//常量指针和指针常量都可以赋值给常量指针 pCntObj->PrintCnt(); *pCntObj = *(Obj2.GetObj()); pCntObj->PrintCnt(); /*const */int nid = pCntObj->GetID();// 常量返回值可以赋值给变量 nid++; cout<<"new nid is:"<<nid<<endl; //*pCntObj = *(Obj1.GetObj());// 常量指针对象,不能进行*p操作,可以进行p++操作 while(1); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |