C++ const成员函数

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;
	}

result
对于const成员函数的两种概念:bitwise constness 和 logical contness,可以理解为,前者要求const成员函数不能在任何情况下更改non-static变量的值,后者是可以在不影响用户使用的情况下对部分成员进行修改。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值