const总结二 之 常量函数形参

来源:互联网 发布:js控制div隐藏 编辑:程序博客网 时间:2024/06/16 08:07

总结:常量函数形参传递参数,保证参数在函数体里面不受修改。有时候,如果形参是指针形参或者引用形参,或者是字符数组,不想函数体对其进行修改,那么可以采用常量函数形参。

实例:

定义EObject类,该类有width和height两个属性,有4个函数对其进行读取和修改。

class EObject{public:EObject(void);~EObject(void);int getWidth(){return this->width;}int getHeight(){return this->height;}void setWidth(int w){this->width = w;}void setHeight(int h){this->height = h;}private:int width;int height;};

 

#include "EObject.h"class Parameter{public:Parameter(void);~Parameter(void);//正常的常量形参void normalParameter(const int i);//const 在*左边的指针形参void pointParameterL(const int* l);//cosnt 在*右边的指针形参void pointParmaeterR(int* const r);//类引用形参void classParmaeter(const EObject& obj);//const在*左边的类指针形参void classParameterL(const EObject* obj);//const在*右边的类指针形参void classParmaeterR(EObject* const obj);};

 

#include "Parameter.h"Parameter::Parameter(void){}Parameter::~Parameter(void){}void Parameter::normalParameter(const int i){//i=10;//error C3892: “i”: 不能给常量赋值}void Parameter::pointParameterL(const int* l){//const在*的左边,代表指针所指内容不能被修改//*l = 10;//error C3892: “l”: 不能给常量赋值}void Parameter::pointParmaeterR(int* const r){//const在*的右边,代表指针不能被修改//r++;// error C3892: “r”: 不能给常量赋值}void Parameter::classParmaeter(const EObject& obj){//后续章节介绍}void classParameterL(const EObject* obj){//后续章节介绍}void Parameter::classParmaeterR(EObject* const obj){//const在*的右边,代表指针不能被修改//obj = new EObject();//error C3892: “obj”: 不能给常量赋值}

  

原创粉丝点击