const对象

总结:
1、const对象不可以引用非const成员函数,只可以调用const成员函数。
2、非const对象既可以调用const成员函数,也可以调用非const成员函数
3、const成员函数不可以改变非multable数据的值。

#include <iostream>

using namespace std;

class area
{
public:
	int x;
	int y; /*假设x,y是银行账户,那么x,y只能都不能写。可以用一个mutable变量来统计查询次数*/
	mutable int z;
	area() :x(10), y(10)
	{
	}
	void printtx0()const
	{
		cout << x << ends << y << endl;
	}
	void printtx1()const
	{
		//x = x + 1;  //const成员函数中不可以改变非mutable数据的值
		z = x + y;    /**/
		cout << x << ends << y << endl;
	}
	int add(int a, int b)
	{
		return 0;
	}
};

void main()
{
	const area area1;
	area1.printtx0(); /*area1是一个const常量,因此可以调用printtx*/
	area1.printtx1();
	//area1.add(1, 2); /*const对象不可以调用非const成员函数*/
	area area2;
	area2.printtx0(); /*area2是一个非const常量,也可以调用printtx*/
	area2.add(3, 5);
	system("pause");
}

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值