7_68.cpp
上传用户:zipjojo
上传日期:2009-07-20
资源大小:70k
文件大小:1k
- #include<iostream.h>
- class sample
- {
- private:
- const int &r;
- const int x;
- static const int y;
- int z;
- public:
- sample(int i,int j);
- void disp()
- {
- cout<<"x="<<x<<",y="<<y<<",r="<<r<<",z="<<z<<endl;
- z++;
- cout<<"x="<<x<<",y="<<y<<",r="<<r<<",z="<<z<<endl;
- cout<<"x+y+z+r="<<gettotal()<<endl; //调用成员函数gettotal()
- cout<<"一般成员函数可更新对象的数据成员!"<<endl;
- }
- int gettotal() {return x+y+z+r;}
- void disp() const;
- };
- sample::sample(int i,int j):x(i),r(x)
- {
- z=j;
- }
- void sample::disp()const
- {
- //z++; //error C2166: l-value specifies const object
- cout<<"x="<<x<<",y="<<y<<",r="<<r<<",z="<<z<<endl;
- // cout<<"x+y+z+r="<<gettotal()<<endl;
- //error C2662: 'gettotal' : cannot convert 'this' pointer from 'const class sample' to 'class //sample &' Conversion loses qualifiers
- cout<<"常成员函数不可更新对象的数据成员!"<<endl;
- cout<<"常成员函数也不能调用该类中没有用const修饰的成员函数!"<<endl;
- }
- const int sample::y=10;
- void main()
- {
- sample a(1,2);
- a.disp();
- cout<<endl<<"常对象只能调用它的常成员函数,不能调用其它成员函数!"<<endl;
- const sample b(3,4);
- b.disp();
- cout<<"x+y+z+r="<<a.gettotal()<<endl;
- // cout<<"x+y+z+r="<<b.gettotal()<<endl;
- // error C2662: 'gettotal' : cannot convert 'this' pointer from 'const class sample' to 'class //sample &' Conversion loses qualifiers
- }