c++ primer 中的 const 关键字理解

1.const  对象只能调用 const成员函数 非const对象两种都可以调用,而非const调用匹配更好。

2.const 函数是承若不修改函数所属对象,即不能修改数据成员。

3.const 数据成员,必须且只有在构造函数的初始化列表中初始化,而const 对象必须初始化。所以申明了const数据成员就必须有个构造函数初始化const数据成员。(构造函数的初始化列表才是真正的初始化数据成员,而函数体是给数据成员赋值)。

4.const 函数的申明是在函数名后加 const 关键字,如 void a() const; 而数据成员的申明是在类型名前 加 const  如 const int i;


#include <iostream>
using namespace std;

class a{
		typedef long index1;
		
	
public:
	a():con(1){};
	void prin( index1 i); 
	void prin(index1 i) const;
	
private:
	 const int con;

};

void a::prin( index1 i )
{

	
		cout<<"this is a common"<<i;
	
}

void a::prin( index1 i ) const
{
	 i=1;
	i++;
	cout<<"this is a const"<<con<<"i="<<i;
}


int _tmain(int argc, _TCHAR* argv[])
{
	a b;
	b.prin(1);
	const a	 c;
	c.prin(1);
	system("pause");
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值