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

  1. 1、有哪些信誉好的足球投注网站(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
  2. 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  3. 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
;在创建类对象后,用 . 和?访问数据成员和成员函数。例如: 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(); /

文档评论(0)

shuwkb + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档