文档详情

第4章类和对象(二)详解.ppt

发布:2017-04-13约1.35万字共56页下载文档
文本预览下载声明
;在创建类对象后,用 . 和?访问数据成员和成员函数。例如: CTest test1; CTest *ptest2=new CTest; //…… couttest1.nendl; coutptest2-nendl;;实际上编译器给成员函数传递一个隐藏的对象指针,指向函数调用所要引用的对象。 函数隐式地使用这个指针。例如: CTest test; test.getn( );;4.1 自引用指针this #includeiostream.h class A{ public: A(int x1){ x=x1; } void disp(){ coutx= xendl;} private: int x; }; main() { A a(1),b(2); cout a: ; a.disp(); cout b: ; b.disp(); return 0; } ;例4.2 显示this指针的值。 #includeiostream.h class A{ public: A(int x1){ x=x1; } void disp() { cout\nthis=thiswhen x=this-x; } private: int x; }; main() { A a(1),b(2),c(3); a.disp(); b.disp(); c.disp(); return 0; } ;this 的定义形式为: T * const this; this 指针是一个常指针,不能在程序中修改或赋值; this指针是一个局部数据,其作用域仅在一个对象内部. #include iostream.h class sample {private: int i,j; public: sample (int x=0,int y=0) { i=x; j=y; } void copy (sample z) { if (this==z) return ; *this=z; coutthis-i\nthis-jendl; coutz.i \nz.jendl; } }; void main() { sample s1,s(2,2); s1.copy (s); } ;4.2 对象数组与对象指针 ;对象数组的应用一: class s {private : int x; public: s(){cout调用构造endl; } void init (int y) {x=y; } int get_x(){ return x; } ~s() {cout调用析构endl; } }; void main() { s sa[2]; sa[0].init(10); sa[1].init(20); for (int i=0;i2;i++) coutsa[i].get_x()/; } ; 对象数组的应用实例??: #include iostream.h class sample { private: int x; public: sample () {x=20;} sample(int i) { x=i; } int get_x(){return x;} }; ;4.2.2 对象指针 ; 例4.7对象指针的使用。 #includeiostream.h class exe{ public: void set_a(int a){ x=a; } void show_a(){ coutxendl; } private: int x; }; main() { exe ob,*p; // 声明类exe的对象ob和类exe的对象指针p ob.set_a(2); ob.show_a(); /
显示全部
相似文档