您的位置:首页 > 编程语言 > C语言/C++

Effective C++——尽可能使用const

2015-09-17 14:05 405 查看

const 关键字威力强大,应用场景很多:指针,迭代器,引用类型,函数参数,函数返回值,类成员函数等

一个复数类Complex

class Complex
{
public:
Complex(int real, int imag) :imag_(imag), real_(real)
{}
~Complex();
friend  const Complex operator* (const Complex& lhs, const Complex& rhs);
void operator= (const Complex& rhs);
bool operator== (const Complex& rhs);

private:
int imag_;
int real_;
};
const Complex operator*(const Complex& lhs, const Complex& rhs)
{
return Complex(lhs.imag_ * rhs.imag_, lhs.real_* rhs.real_);
}
void Complex::operator=(const Complex& rhs)
{
this->imag_ = rhs.imag_;
this->real_ = rhs.real_;
}
bool Complex::operator==(const Complex& rhs)
{
if (this->imag_ == rhs.imag_ && this->real_ == rhs.real_)
{
return true;
}
else
{
return false;
}
}


运算符重载时,const 用来修饰函数返回值的必要性

friend const Complex operator* (const Complex& lhs, const Complex& rhs);

场景1:为什么有人会对两个数值的乘积再做一次赋值?——客户端暴行

Complex com1(2, 3);
Complex com2(4, 3);
Complex com3(5, 3);
com1*com2 = com3;//没有const 修饰编译通过,加const 编译报错
if(com1*com2 = com3)//没有const 修饰编译通过,加const 编译报错
{
内置类型直接提示这样的赋值操作不合法,所以自定义类型应该也具有这样的功能,但如果不加const 就没有这样的功能。
}


const 用来修饰成员函数,修饰的是this指针(non-static 成员除外),可以构成重载

作用1:使得接口意图明显

作用2:操作const对象变为可能

一个文本类

class Text
{
public:
const char& operator[](std::size_t position) const //后一个const构成重载
{
return text[position];
}
char& operator[](std::size_t position)
{
return text[position];
}
private:
std::string text;
};
void print(const Text& obj)
{
cout<<obj[0]<<endl;
obj[0] = 's';//返回的是const引用,表示引用的空间不可写.要是const char类型会怎么样呢?
**对于函数返回值是内置类型的情况,改动返回值是不合法的,编译就会报错。退一步讲,即使合法,那么C++中By value返回对象这一特性表明被改动的其实是一个副本,也没有什么意义。**
}


const 修饰成员函数时,mutable 可去除non-static 成员变量的const属性

在const 和non-const 成员函数中避免代码重复

const char& operator[](std::size_t position) const
{
//TODO:一系列工作
return  text[position];
}
char& operator[](std::size_t position)
{
return const_cast<char&>(static_cast<const Text&>(*this)[position]);
}


说明:
1.non-const函数如何调用const 函数
a)(*this)[position]表示调用[]运算符重载函数
b)static_cast<const Text&>(*this)[position],很关键的一步,表示将non-const对象转化为const对象,这样调用的就是const修饰的重载函数
c)需要将const修饰的函数返回值转化为char&,需要用到const_cast<char&>,去const属性
2.这样避免代码重复,特别当运算符[]重载函数里面需要完成很多工作时。
3.千万不要使用在const修饰的函数中调用non-const函数去实现以上同样的效果,因为non-const函数不承诺会不改变对象的逻辑状态。真要这么做,首先就需要const_cast<Text&>(*this)[position],去掉对象的const属性,但这明显和const修饰的函数本身意义相驳了,const含义是保持对象不变。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: