目录
1.physical constness (对象物理空间不能改变)
1.cosnt修饰指针
char greeting[] = "hello"
char * p = greeting;,指针可修改,指向内容可以修改。
cosnt char *p = greetng; ,指针可修改,指向内容不可以修改。
char * cosnt p = greetng;,指针不可修改,指向的容可以修改。
const char * const p = greeting;,指针不可修改,指向内容不可以修改。
const出现在 * 的左边修饰指针指向的内容,出现在 * 的右边修饰指针本身。
fun1(const A * pa)和fun2( B const * pb) pa和pb都是指向的内容不可改变。
2.cosnt修饰迭代器
迭代器是由指针塑模出来了,修饰迭代器就相当于修饰指针本身。
vector<int> vec;
const vector<int> :: iterator iter = vec.begin();
*iter = 20;正确 可以修改
iter++;错误指针本身不可以修改
如果想要指向的内容不可修改应该使用const迭代器
vector<int>::const_iterator Citer = vec.begin();
*iter = 20;错误const_iterator迭代器内容不可修改
iter++;正确指针本身可以修改
3.const修饰函数返回值
如果一个函数返回值是不需要改动的,一定要加上const,防止用户未确定的行为。
class Rational {.......};
例: const Rational operator*(const Rational &lhs,const Rational &rhs)
Rational a,b,c;
(a * b) = c;//在a * b的结果上调用operator=这个是一个无意义的行为,内置类型也不支持这样操作,在运算符重载的时候,要于内置类型一致。
4.const成员函数
针对const成员函数主要有两种说法
1.physical constness (对象物理空间不能改变)
这种说法主张const 成员函数,不可以更改成员变量的任何非non-static变量。
一个更改了指针所指物,成员函数不能算作const,但是如果所指物,不隶属于对象,称为physical constness
例:
class A
{.......................
public:
char& operator[](size_t postion) const //physical constnes声明
{
return _str[postion];
}private:
char* _str;
};int main()
{
const A a ("hello");
a[0] = 'j';}
这样就得到了jello
编译器检查采用的是physical constness检查,但是编写程序要用"概念上的常量性".
2.logical constness
这一派主张const成员函数可以修改他所处理对象的一部分bits
例:
class B
{
public:
size_t modlenth(int newlen) const
{
_lenth = newlen;
}private:
char* _str;
mutable size_t _lenth;
};
只需要在成员变量的前面加上mutable(可修改的)就可以释放physical constness的约束
5.const和非const成员函数中避免重复
class C
{
public:
const char& operator[](size_t postion) const
{
return _str[postion];
}char& operator[](size_t postion)
{
return const_cast<char&>( //3.把const成员函数返回值的const去掉static_cast <const C&>(*this)//1.先把转化为const对象
[postion]);//2.调用const成员函数
}private:
char* _str;
};