C++程序设计第十讲.ppt

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

C++程序语言设计 Chapter 10: the Copy-Constructor Outline Passing returning by value Problem with the Bitcopy Copy-construction Default copy-constructor Pointers to members Passing returning by value types built into the compiler int f(int x, char c); int g = f(a, b); user-defined types struct Big {char buf[100]; int i; long d;} B, B2; Big bigfun(Big b) { b.i = 100; // Do something to the argument return b; } int main() { B2 = bigfun(B); } Problem with the Bitcopy For passing and returning large simple structures, there is a way to copy the bits from one place to another. int a = 3; int b; b = a; in C++ objects can be much more sophisticated than a patch of bits. Problem with the Bitcopy See the file: HowMany.cpp class A{ public:A(){name = NULL;age = 20;} void Init(int size, int age){name = new char[size];this.age = age;} int getAge(){return age;} Private:char *name; int age; //类的对象中包含指针成员,指向动态分配内存资源 (即指向堆中分配的一内存空间) }; /*生成一个对象: A objA;objA.Init(20, 45);A objB = objA; //这时用objA初始化objB, 即必须把objA内的数据成员值赋给objB的数据成员 //即 objB.name = objA.name;objB.age = objA.age; 由于直接objB.name = objA.name;所以这时objB.name和objA.name同时指一个堆内存区域,从而产生了对象的内存不独立的情况 */ Copy-construction the compiler makes an assumption about how to create a new object from an existing object HowMany h2 = f(h); the copy-constructor --- X(X) this function is a constructor the single argument to this constructor has to the object be constructing from the reference of the source object Copy-construction If you create a copy-constructor, the compiler will not perform a bitcopy when creating a new object from an existing one. It will always call your copy-constructor. See the file: HowMany2.cpp Temporary objects It turns out the compiler can create a temporary object whenever it needs one to properly evaluate an expression. The lifetime of this temporary object is as short as possible the temporary might immediately be passed to another function the function call ends the temporary object is destroyed D

文档评论(0)

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

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

1亿VIP精品文档

相关文档