1.迭代器const
std::vector<int> vec;
...
const std::vector<int>::iterator iter = // iter acts like a T* const
vec.begin();
*iter = 10; // OK, changes what iter points to
++iter; // error! iter is const
//
std::vector<int>::const_iterator cIter = // cIter acts like a const T*
vec.begin();
*cIter = 10; // error! *cIter is const
++cIter; // fine, changes cIter
记住就好
2.函数const
在一个函数声明,const 既可以用在函数的 返回值,也可以用在个别的参数,对于 成员函数,还可以用于整个函数。
特别的是 对于成员函数的整个const 代表 不修改该对象的任何成员变量
在函数的最后面加const 和不加const是两个函数 是重载的!!!
3.*运算符重载
//返回值为const Rational
const Rational operator*(const Rational& lhs, const Rational& rhs);
Rational a, b, c;
...
(a * b) = c; // invoke operator= on the
// result of a*b!
if (a * b = c) ... // oops, meant to do a comparison!
//少了一个等号 如果是const 会报错
为了防止这样的出现 (a*b) 若不是const (a * b = c)不会报错
3.const成员函数
class TextBlock {
public:
...
const char& operator[](std::size_t position) const // operator[] for
{ return text[position]; } // const objects
char& operator[](std::size_t position) // operator[] for
{ return text[position]; } // non-const objects
private:
std::string text;
};
void print(const TextBlock& ctb) // in this function, ctb is const
{
std::cout << ctb[0]; // calls const TextBlock::operator[]
...
}
TextBlock tb("Hello");
std::cout << tb[0]; // calls non-const
// TextBlock::operator[]
const TextBlock ctb("World");
std::cout << ctb[0]; // calls const TextBlock::operator[]
4.位不变和逻辑不变
如char* txt=“hello"; 改变其hello的值 text指针的位置并未发生改变
class CTextBlock {
public:
...
char& operator[](std::size_t position) const // inappropriate (but bitwise
{ return pText[position]; } // const) declaration of
// operator[]
private:
char *pText;
};
const CTextBlock cctb("Hello"); // declare constant object
char *pc = &cctb[0]; // call the const operator[] to get a
// pointer to cctb's data
*pc = 'J'; // cctb now has the value "Jello"const CTextBlock cctb("Hello"); // declare constant object
char *pc = &cctb[0]; // call the const operator[] to get a
// pointer to cctb's data
*pc = 'J'; // cctb now has the value "Jello"
5.mutable
class CTextBlock {
public:
...
std::size_t length() const;
private:
char *pText;
mutable std::size_t textLength; // these data members may
mutable bool lengthIsValid; // always be modified, even in
}; // const member functions
std::size_t CTextBlock::length() const
{
if (!lengthIsValid) {
textLength = std::strlen(pText); // now fine
lengthIsValid = true; // also fine
}
return textLength;
}
6.去除重复代码
定义const的函数 在no const中调用
class TextBlock {
public:
TextBlock(const std::string& text) : text(text) {}
const char& operator[](std::size_t position) // operator[] for
{
return text[position];
} // non-const objects
const char& operator[](std::size_t position) const // operator[] for
{
return const_cast<char&>
(static_cast<const TextBlock*>(this)->text[position]);
} // const objects
private:
std::string text;
static int static_var ;
};