C++笔记12

常量对象、常量成员函数和常引用

常量对象
如果不希望某个对象的值被改变,则定义该对象的时候可以在前面加上 const 关键字
exp.

class Demo{
private:
int value;
public:
void SetValue(){  }
};
const Demo Obj;//常量对象 这个Obj就不能再后续修改其值

常量成员函数
在类的成员函数说明后面可以加上 const 关键字,则该成员函数为常量成员函数

常量成员函数执行期间不应修改其所作用的对象。因此,在常量成员函数中不能修改成员变量的值(静态成员变量除外),也不能调用同类的非常量成员函数(静态成员函数除外) 因为静态被所有对象所共享
exp.

class Sample
{
public:
int value;
void GetValue() const;
void func(){};
Sample(){}
};
void Sample::GetValue() const
{
value=0;//wrong
func();//wrong
}

int main(){
const Sample o;
o.value=100;//error 常量对象不可被修改
o.func();//error常量对象上面不能执行费常量成员函数
o.GetValue();//ok
return 0;
}

常量成员函数的重载
两个成员函数,名字和参数表都一样,但是一个是const,一个不是,算重载

class CTest{
private:
int n;
public:
CTest(){n=1;}
int GetValue() const {return n;}
int GetValue() {return 2*n;}
};
int main(){
const CTest objTest1;
CTest objTest2;
cout<<objTest1.GetValue()<<","<<objTest2.GetValue();
return 0;
}

常引用
引用前面可以加const关键字,成为常引用。不能通过常引用修改其引用的变量
exp.

const int &r=n;
r=5;//error
n=4;//ok

为防止对象引用产生的开销,我们可以用对象的引用作为参数
exp.

class Sample{
...
};
void PrintfObj(Sample & o)//o不是参数,就可以节省了复制构造函数的开销
{
...
}

常引用更好
exp.

class Sample{
...
};
void PrintfObj(const Sample & o)
{
...
}

猜你喜欢

转载自www.cnblogs.com/AirBirdDD/p/12286773.html