C ++ const常量对象,常量成员函数和常量引用

C ++ const常量对象,常量成员函数和常量引用

& nbsp;小林编码-  1  —常量对象如果您不希望更改对象的值,则可以在定义对象时在其前面添加const关键字。

class Ctest {public:& nbsp;& nbsp;& nbsp;& nbsp; void& nbsp; SetValue()& nbsp; {} private:& nbsp;& nbsp;& nbsp ;& nbsp; int& nbsp; m_value;}; const& nbsp; CTest obj; //常量对象-& nbsp; 2& nbsp;-常量成员函数可以在类的成员函数之后添加const关键字,并且该成员函数成为常量成员函数。

这里有两点需要注意:不能在常量成员函数中修改成员变量的值(静态成员变量除外);也不能调用类似的非恒定成员函数(静态成员函数除外)。

class& nbsp; Sample {public:& nbsp;& nbsp;& nbsp;& nbsp; void& nbsp; GetValue()& nbsp; const& nbsp; {} //常量成员函数& nbsp;& ; nbsp;& nbsp; void& nbsp; func(){}& nbsp;& nbsp;& nbsp;& nbsp; int& nbsp; m_value;}; void& nbsp;样品: :GetValue()const ///常量成员函数{& nbsp;& nbsp;& nbsp; value = 0; //错误& nbsp;& nbsp;& nbsp; func(); //错误} int& nbsp; main(){& nbsp;& nbsp;& nbsp;& nbsp; const& nbsp;示例obj;& nbsp;& nbsp;& nbsp;& nbsp ; obj.value = 100;& nbsp; //错误,常量对象不能为Modify& nbsp;& nbsp;& nbsp; obj.func();& nbsp; & nbsp;& nbsp; //发生错误,并且无法在常量对象上执行非常数成员函数。

; & nbsp; //好了,可以在常量对象上执行常量成员函数& nbsp;& nbsp;& nbsp;& nbsp;& nbsp;& nbsp;& nbsp; return& nbsp; 0 ;} — 3  —常量成员函数重载了两个成员函数,名称与参数列表相同,但一个为const,另一个为非,因此被视为重载。

class& nbsp; Sample {public:& nbsp;& nbsp;& nbsp;& nbsp; Sample(){m_value = 1; }& nbsp;& nbsp;& nbsp; int& nbsp; GetValue()& nbsp; const& nbsp; {return& nbsp; m_value;} //常量成员Function& nbsp;& nbsp;& nbsp; int& nbsp; GetValue()& nbsp; {return& nbsp; 2 * m_value;} //普通成员函数& nbsp;& nbsp;& nbsp;& nbsp ; int& nbsp; m_value;}; int& nbsp; main(){& nbsp;& nbsp;& nbsp;& nbsp; const& nbsp;样本obj1;& nbsp;& nbsp;& nbsp;& nbsp; std :: cout& lt;<< “常数成员函数”<<<<< obj1.GetValue()& lt;& lt; std :: endl;& nbsp;& nbsp;& nbsp;& nbsp;& nbsp;& nbsp;& nbsp;示例obj2;& nbsp;& nbsp;& nbsp;& nbsp; std :: cout& lt;<< <<><<<<<> obj2.GetValue()& lt;& lt; std :: endl;}执行结果:常量成员函数1普通成员函数2-& nbsp; 4& nbsp;-常量引用之前可以带有const关键字,以成为常量引用。

无法通过常量引用修改引用的变量。

const& nbsp;& amp; amp; r = n; r = 5; // errorn = 4; // 好的!当将对象用作函数参数时,必须调用复制构造函数以生成对象参数,因此效率相对较低。

用指针作为参数,代码不好看,怎么解决呢?您可以将对象引用用作防止复制构造函数被触发的参数,例如:class& namp; Sample {& nbsp;& nbsp;& nbsp;& nbsp; ...}; void& nbsp; Func(Sample& o)&//对象引用作为参数{& nbsp;& nbsp;& nbsp;& nbsp; ...},但是存在问题。

对象引用作为函数参数具有一定的风险。

如果在函数中意外修改了形式参数o,则实际参数也会更改。

这可能不是我们想要的,如何避免呢?您可以使用对象的常量引用作为参数,例如:class& nbsp; Sample {& nbsp;& nbsp;& nbsp;& nbsp; ...}; void& nbsp; Func(const& ; nbsp; Sample& o)& nbsp; //对象的常数引用作为参数{& nbsp;& nbsp;& nbsp;& nbsp; ...},该函数可以确保不存在意外更改o值的语句。

推荐阅读:C ++此指针的理解和功能C ++静态静态成员C ++成员对象和封闭的类小林编码

深圳市相信过程科技有限公司❤舒先生❤欢迎您的咨询