#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