将某些东西声明为const可以帮助编译器检测出错误用法,const
编译器强制实施bitwise constness,但是你code的时候应该使用“概念上的常量性”
当const和non-const成员函数有着实质等价的实现时,令non-const版本调用const版本可以避免代码重复。
0)迭代器类似T*指针,声明迭代器为const就像声明指针为const一样。(即声明一个T* const指针)
如果你希望迭代器所指的不能被改动,需要的是const_iterator
vector<int>::iterator iter = vec.begin();//iter作用像T* const
*iter = 10;//没问题,改变iter所指物
iter++;//错误,iter是const
vector<int>::const_iterator cIter = vec.begin();//作用像const T*
*cIter = 10;//错误 *cIter是const
iter++;//OK
返回值为const 防止(a*b)=c;这样的暴行
1)const成员函数之所以重要,因为a)知道哪个函数可以改动对象内容;b)使得“操作const对象”成为可能。
两个成员函数如果只是常量性(constness)不同,可以被重载。
#include <iostream>
#include <string.h>
using namespace std;
class TextBlock
{
private:
char text[256];
public:
TextBlock(char *input)
{
strcpy(text,input);
}
//!!!REMEMBER IT!!!!
//operator[] for const object
const char& operator[](std::size_t position) const
{
cout << "now in the const member\n";
return text[position];
}
//operator[] for non-const object
char& operator[](std::size_t position)
{
cout << "now in the non-const member\n";
return text[position];
}
};
int main()
{
TextBlock tb("hello");
cout << tb[0] <<'\n';
const TextBlock ctb("world");
cout << ctb[0] <<'\n';
return 0;
}
now in the non-const member
h
now in the const member
w
2)在const和non-const成员函数中避免重复
class TextBlock
{
public:
const char& operator[](size_t position) const
{ //bounds checking,log access data,verify data integrity...
return text[position];
}
char& operator[](size_t position)//现在只调用const op[]
{
return const_cast<char&>(//将op[]返回值的const转除
static_cast<const TextBlock&>(*this)[position]);//为*this加上const调用const op[]
}//代码写的真巧妙,我这辈子估计都写不出这么巧妙的代码了。。。。
};