const

const成员函数必须在声明和定义时都注明const

Declaring a member function with the const keyword specifies that the function is a "read-only" function that does not modify
the object for which it is called.
To declare a constant member function, place the const keyword after the closing parenthesis of the argument list.
The const keyword is required in both the declaration and the definition. A constant member function cannot modify any data members
or call any member functions that aren't constant.

 const member variable can only be initialized in constructor initialization list.

下例用来说明:

1)const成员函数不能修改成员变量

2)非const成员函数可以访问const和非const成员变量,但不能修改const成员变量

class Base_const
{
public:
	void fun() const;
	void nonconst_fun_access_const_var();
	Base_const(int x):i(1),c(x) {}
private:
	int i;
	const int c;
};

void Base_const::fun() const
{
	//i=4; //const成员函数不能修改成员变量
	cout << "i= "<<i <<endl<<"c=" << c <<endl;
	
	nonconst_fun();//error: non_const function can't be called by const function

};

//非const成员函数可以访问const和非const成员变量,但不能修改const成员变量
void Base_const::nonconst_fun()
{
	c++; //error:不能修改const成员变量
	i++;
	cout << c <<endl;
	cout << i <<endl;
}
#endif /* MYCONST_H_ */


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值