第6章 类和对象gai.ppt

第6章 类和对象gai

* * * //例6.8——Cat..h class cat { private: int age; float weight; char *color; public: cat(); cat(cat ); void play(); void hunt(); }; cat::cat() { age=1;weight=10;color=cat;} cat::cat(cat other) { age = other.age; weight=other.weight; color = other.color; } void cat::play() { coutplaycolor;} void cat::hunt() {couthuntage;} //Catmain.cpp #includeiostream.h #includekcopy.h void main() { cat cat1,cat2(cat1); cat1.play(); cat2.hunt(); } * void fun1(Point p) { coutp.GetX()endl; } void main() { Point A(1,2); fun1(A); //调用拷贝构造函数 } * * 原因是浅拷贝只拷贝对象的数据成员,而不拷贝指针数据成员所指区域,这样,就使得两个对象的指针数据成员指向了同一块内存空间,这样可带来两个方面的问题: 一是一方对象的改变会直接影响到另一方对象,因为它们有指针数据成员指向同一块内存单元; 二是资源归属不清,引起资源管理的混乱,易产生悬挂指针问题,即一方删除对象后另一方就会成为悬挂指针,也就是说,会导致同一块内存单元的两次释放。 * 单线箭头表示类中的指针数据成员指向堆区域中的存储空间,双线箭头表示对象中各数据成员的拷贝。 本例中,由对象obj1生成对象obj2的方法采用的是深拷贝。 例如:Person p1(“wangmin”); Person p2(p1); * * * * * * * * * * * * * * 题题7.分析以下程序的执行结果 #includeiostream.h class Sample { char c1,c2; public: Sample(char a){c2=(c1=a)-32;} void disp() { coutc1转换为c2endl; } }; ? void main() { Sample a(a),b(b); a.disp(); b.disp(); } 题8.分析以下程序的执行结果 #includeiostream.h class Sample { int x; int y; public: Sample(int a,int b) { x=a;y=b; } int getx(){return x;} int gety(){return y;} }; ? void main() { int (Sample::*fp)(); fp=Sample::getx; Sample s(2,7); int v=(s.*fp)(); fp=Sample::gety; int t=(s.*fp)(); coutv=v,t=tendl; } 题9. 分析以下程序的执行结果 #includeiostream.h class Sample { int x,y; public: Sample(){x=y=0;} Sample(int a,int b){x=a,y=b;} void disp() { coutx=x,y=yendl; } }; ? void main() { Sample s1,s2(1,2),s3(10,20); Sample *Pa[3]; Pa[0]=s1; Pa[1]=s2; Pa[2]=s3; for(int i=0;i3;i++) Pa[i]-disp(); } 题10.分析以下程序的执行结果 #includeiostream.h class Sample { int x,y; public: Sample(){x=y=0;} Sample(int a,int b){x=a,y=b;} ~Sample() { if(x==y) coutx=yendl; else coutx!=yendl; } void disp() {

文档评论(0)

1亿VIP精品文档

相关文档