C++ 常量成员常量返回值详解

2019/7/10 22:46:31

本文主要是介绍C++ 常量成员常量返回值详解,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

总结:
1.常量数据成员,形式:const Type m_tData;
1)常量数据成员,需要在构造函数列表中给出,构造函数中可以用常量赋值,也可以实例化的时候赋值。
2)赋值函数中不能赋值,起到保护常量数据成员的作用,和友元作用相反。

2.常量成员函数,形式:type funname(type1 arg1,type2 arg2,...) const
1)常量成员函数,不能修改类数据成员,不能调用非常量函数。
2)常量成员函数的作用,可以有效的将类的函数分为可以修改类的函数,和不能修改类的函数;以后应该善于使用常量成员函数。

3.返回常量的函数,可以是常量指针,指针常量,常量,形式:
const type* funcname(type1 arg1,type2 arg2, ..)
type* const funcname(type1 arg1,type2 arg2, ..)
const funcname(type1 arg1,type2 arg2, ..)
他们的返回类型对于使用不是重要的,重要的是赋给的对象的类型决定了后续能够进行的操作。
常量指针和指针常量都可以赋值给常量指针对象,常量指针对象可以进行p++操作,不能进行*p操作。
常量指针和指针常量都可以赋值给指针常量,但是指针常量只能进行*p操作,不能进行p++操作。
普通类型的返回常量的函数,目的是为了让成员函数返回值之间不能进行运算,防止产生丑陋的代码,
返回值是常量的函数,说明该类内的这个值是外部使用者不能轻易改变的, 可以让类的声明的含义更加贴切,更加易于理解。

#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);
}


这篇关于C++ 常量成员常量返回值详解的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程