C++ 字符串 21-- 18.56.const对象与const成员

80 篇文章 0 订阅
#include <iostream>
//#include <string>
using namespace std;
/*---------------------------------
18.56.const对象与const成员
---------------------------------*/
class A
{
public:
	A(int i,int j){x=i;y=j;}
	void set(int s1,int s2){x=s1;y=s2;}
	void print()
	{	cout<<x<<endl;}      //一般成员函数
	void print()const //const修饰函数定义体,即变成const成员函数,定义体中不能修改任何类成员变量
	{
		cout<<y<<endl;
		//y=6; //const成员函数,不能修改任何类的成员变量
		//set(2,6);//const成员函数中不许调用非const成员函数,编译报错
	}    //error C2662: 'set' : cannot convert 'this' pointer from 'const class A' to 'class A &'
private:
	int x,y;
};
int main()
{
	const A a(2,3);
	a.print();//const对象只能调用const成员函数
	cout<<"----------"<<endl;
	A b(4,5); //非const对象只能调用非const成员函数
	b.print();


	return 0;
}
运行结果:
3
----------
4
Press any key to continue

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值