Const关键字
const可以用于替换#define
使用宏定义可能并不会加入记号表(symbol table)
例如:
#define PI 3.14159
const double Pi = 3.14159;
而对于const与指针同时出现的情况:如果const在’* ’ 左侧,则被指物为常量;如果const在’* '右侧,则指针本身为常量;如果出现两次,则都为常量。
const TreeNode* root;//
TreeNode const * root;//exactly the same
const成员函数,此处重载operator[],且两种给予不同的返回值类型,使得const和non-const对象获得不同的处理。而且因为返回值类型的区别,也就对赋值操作进行了限制。
class TestConst {
public:
TestConst();
TestConst(const char* s);
const char& operator[](size_t pos) const {//const 对象
return test[pos];
}
char& operator[](size_t pos) {//non-const 对象
return test[pos];
}
friend ostream& operator<<(ostream& os, TestConst t);
private:
string test;
};
TestConst::TestConst(const char* c) :test(c){
cout << test << ": " << typeid(c).name() << endl;
}
ostream& operator<<(ostream& os, TestConst t) {
int size = t.test.size();
for (int i = 0; i < size;++i) {
os << t[i];
}
return os;
}
int main (){
char name[6]="Hello";
//cout << typeid(name).name() << endl;
TestConst tb(name);
const TestConst ctb("this");
//cout << typeid(ctb).name() << endl;
cout << "ctb: " << ctb << endl;
cout << "tb: " << tb << endl;
//ctb[0] = 'k'; // illegal
tb[0] = 'Y';
cout << "tb: " << tb << endl;
return 0;
}
对于const成员函数的两种概念:bitwise constness 和 logical contness,可以理解为,前者要求const成员函数不能在任何情况下更改non-static变量的值,后者是可以在不影响用户使用的情况下对部分成员进行修改。