欢迎来到三一办公! | 帮助中心 三一办公31ppt.com(应用文档模板下载平台)
三一办公
全部分类
  • 办公文档>
  • PPT模板>
  • 建筑/施工/环境>
  • 毕业设计>
  • 工程图纸>
  • 教育教学>
  • 素材源码>
  • 生活休闲>
  • 临时分类>
  • ImageVerifierCode 换一换
    首页 三一办公 > 资源分类 > PPT文档下载  

    C++教程英文版.ppt

    • 资源ID:6153960       资源大小:1.05MB        全文页数:85页
    • 资源格式: PPT        下载积分:15金币
    快捷下载 游客一键下载
    会员登录下载
    三方登录下载: 微信开放平台登录 QQ登录  
    下载资源需要15金币
    邮箱/手机:
    温馨提示:
    用户名和密码都是您填写的邮箱或者手机号,方便查询和重复下载(系统自动生成)
    支付方式: 支付宝    微信支付   
    验证码:   换一换

    加入VIP免费专享
     
    账号:
    密码:
    验证码:   换一换
      忘记密码?
        
    友情提示
    2、PDF文件下载后,可能会被浏览器默认打开,此种情况可以点击浏览器菜单,保存网页到桌面,就可以正常下载了。
    3、本站不支持迅雷下载,请使用电脑自带的IE浏览器,或者360浏览器、谷歌浏览器下载即可。
    4、本站资源下载后的文档和图纸-无水印,预览文档经过压缩,下载后原文更清晰。
    5、试题试卷类文档,如果标题没有明确说明有答案则都视为没有答案,请知晓。

    C++教程英文版.ppt

    1,10,Classes:ADeeper Look,Part 2,2,10.1 Introduction,const objects and const member functionsPrevent modifications of objects Enforce the principle of least privilegeCompositionClasses having objects of other classes as membersFriendshipEnables class designer to specify that certain non-member functions can access the classs non-public members,3,10.1 Introduction(Cont.),this pointerDynamic memory managementnew and delete operatorsstatic class membersProxy classes Hide implementation details of a class from clientsPointer-base stringsUsed in C legacy code from the last two decades,4,10.2 const(Constant)Objects and const Member Functions,Principle of least privilege One of the most fundamental principles of good software engineeringApplies to objects,tooconst objectsKeyword constSpecifies that an object is not modifiable Attempts to modify the object will result in compilation errors,5,10.2 const(Constant)Objects and const Member Functions(Cont.),const member functionsOnly const member function can be called for const objectsMember functions declared const are not allowed to modify the object A function is specified as const both in its prototype and in its definitionconst declarations are not allowed for constructors and destructors,6,Software Engineering Observation 10.2,A const member function can be overloaded with a non-const version.The compiler chooses which overloaded member function to use based on the object on which the function is invoked.If the object is const,the compiler uses the const version.If the object is not const,the compiler uses the non-const version.,7,Common Programming Error 10.4,Attempting to declare a constructor or destructor const is a compilation error.,8,Outline,Time.h(1 of 2),const keyword to indicate that member function cannot modify the object,9,Outline,Time.h(2 of 2),10,Outline,Time.cpp(1 of 3),11,Outline,Time.cpp(2 of 3),12,Outline,Time.cpp(3 of 3),13,Outline,fig10_03.cpp(1 of 2),Cannot invoke non-const member functions on a const object,14,Outline,fig10_03.cpp(2 of 2),15,10.2 const(Constant)Objects and const Member Functions(Cont.),Member initializer Required for initializingconst data membersData members that are referencesCan be used for any data memberMember initializer listAppears between a constructors parameter list and the left brace that begins the constructors bodySeparated from the parameter list with a colon(:)Each member initializer consists of the data member name followed by parentheses containing the members initial valueMultiple member initializers are separated by commasExecutes before the body of the constructor executes,16,Outline,Increment.h(1 of 1),const data member that must be initialized using a member initializer,17,Outline,Increment.cpp(1 of 1),Colon(:)marks the start of a member initializer list,Member initializer for non-const member count,Required member initializer for const member increment,18,Outline,fig10_06.cpp(1 of 1),19,Outline,Increment.h(1 of 1),Member function declared const to prevent errors in situations where an Increment object is treated as a const object,20,Outline,Increment.cpp(1 of 1),It is an error to modify a const data member;data member increment must be initialized with a member initializer,21,Outline,fig10_09.cpp(1 of 2),22,Outline,fig10_09.cpp(2 of 2),23,10.3 Composition:Objects as Members of Classes,CompositionSometimes referred to as a has-a relationshipA class can have objects of other classes as membersExampleAlarmClock object with a Time object as a member,24,10.3 Composition:Objects as Members of Classes(Cont.),Initializing member objectsMember initializers pass arguments from the objects constructor to member-object constructorsMember objects are constructed in the order in which they are declared in the class definitionNot in the order they are listed in the constructors member initializer listBefore the enclosing class object(host object)is constructedIf a member initializer is not providedThe member objects default constructor will be called implicitly,25,Software Engineering Observation 10.6,Member objects are constructed in the order in which they are declared in the class definition(not in the order they are listed in the constructors member initializer list)and before their enclosing class objects(sometimes called host objects)are constructed.,26,Outline,Date.h(1 of 1),27,Outline,Date.cpp(1 of 3),28,Outline,Date.cpp(2 of 3),29,Outline,Date.cpp(3 of 3),30,Outline,Employee.h(1 of 1),Parameters to be passed via member initializers to the constructor for class Date,const objects of class Date as members,31,Outline,Employee.cpp(1 of 2),Member initializers that pass arguments to Dates implicit default copy constructor,32,Outline,Employee.cpp(2 of 2),33,Outline,fig10_14.cpp(1 of 2),Passing objects to a host object constructor,34,Outline,fig10_14.cpp(2 of 2),35,10.4 friend Functions and friend Classes,friend function of a class Defined outside that classs scopeNot a member function of that classYet has the right to access the non-public(and public)members of that classStandalone functions or entire classes may be declared to be friends of a class Can enhance performanceOften appropriate when a member function cannot be used for certain operations,36,10.4 friend Functions and friend Classes(Cont.),To declare a function as a friend of a class:Provide the function prototype in the class definition preceded by keyword friendTo declare a class as a friend of a class:Place a declaration of the form friend class ClassTwo;in the definition of class ClassOneAll member functions of class ClassTwo are friends of class ClassOne,37,10.4 friend Functions and friend Classes(Cont.),Friendship is granted,not takenFor class B to be a friend of class A,class A must explicitly declare that class B is its friendFriendship relation is neither symmetric nor transitiveIf class A is a friend of class B,and class B is a friend of class C,you cannot infer that class B is a friend of class A,that class C is a friend of class B,or that class A is a friend of class C It is possible to specify overloaded functions as friends of a classEach overloaded function intended to be a friend must be explicitly declared as a friend of the class,38,Software Engineering Observation 10.10,Some people in the OOP community feel that“friendship”corrupts information hiding and weakens the value of the object-oriented design approach.In this text,we identify several examples of the responsible use of friendship.,39,Outline,fig10_15.cpp(1 of 2),friend function declaration(can appear anywhere in the class),40,Outline,fig10_15.cpp(2 of 2),friend function can modify Counts private data,Calling a friend function;note that we pass the Count object to the function,41,Outline,fig10_16.cpp(1 of 3),42,Outline,fig10_16.cpp(2 of 3),Non-friend function cannot access the classs private data,43,Outline,fig10_16.cpp(3 of 3),Classes Part II,friend Class Example,/ClassTwo Interface class ClassTwo friend class ClassOne;public:/constructor ClassTwo():x(0),y(0),z(0)/no body void print()const cout x=x endl;cout y=y endl;cout z=z endl;private:int x,y,z;/data members void setX(int val)x=val;void setY(int val)y=val;void setZ(int val)z=val;,/ClassOne Interface#include“classtwo.h”class ClassOne public:void setX(int val)c.x=val;void setY(int val)c.y=val;void setZ(int val)c.z=val;void print()const cout x=c.x endl;cout y=c.y endl;cout z=c.z endl;private:ClassTwo c;,Classes Part II,CIS 554/45,friend Class Exampletest driver and output,#include classone.hvoid main()ClassOne c1;c1.print();c1.setX(5);c1.setY(10);c1.setZ(15);c1.print();,46,10.5 Using the this Pointer,Member functions know which objects data members to manipulate Every object has access to its own address through a pointer called this(a C+keyword)An objects this pointer is not part of the object itselfThe this pointer is passed(by the compiler)as an implicit argument to each of the objects non-static member functionsObjects use the this pointer implicitly or explicitlyImplicitly when accessing members directlyExplicitly when using keyword thisType of the this pointer depends on the type of the object and whether the executing member function is declared const,47,Outline,fig10_17.cpp(1 of 2),48,Outline,fig10_17.cpp(2 of 2),Implicitly using the this pointer to access member x,Explicitly using the this pointer to access member x,Using the dereferenced this pointer and the dot operator,49,10.5 Using the this Pointer(Cont.),Cascaded member-function callsMultiple functions are invoked in the same statementEnabled by member functions returning the dereferenced this pointerExamplet.setMinute(30).setSecond(22);Calls t.setMinute(30);Then calls t.setSecond(22);,50,Outline,Time.h(1 of 2),set functions return Time&to enable cascading,51,Outline,Time.h(2 of 2),52,Outline,Time.cpp(1 of 3),Returning dereferenced this pointer enables cascading,53,Outline,Time.cpp(2 of 3),54,Outline,Time.cpp(3 of 3),55,Outline,fig10_20.cpp(1 of 2),Cascaded function calls using the reference returned by one function call to invoke the next,Note that these calls must appear in the order shown,because printStandard does not return a reference to t,56,Outline,fig10_20.cpp(2 of 2),57,10.6 Dynamic Memory Management with Operators new and delete,Dynamic memory managementEnables programmers to allocate and deallocate memory for any built-in or user-defined typePerformed by operators new and deleteFor example,dynamically allocating memory for an array instead of using a fixed-size array,58,10.6 Dynamic Memory Management with Operators new and delete(Cont.),Operator newAllocates(i.e.,reserves)storage of the proper size for an object at execution timeCalls a constructor to initialize the objectReturns a pointer of the type specified to the right of new Can be used to dynamically allocate any fundamental type(such as int or double)or any class typeFree storeSometimes called the heapRegion of memory assigned to each program for storing objects created at execution time,59,10.6 Dynamic Memory Management with Operators new and delete(Cont.),Operator deleteDestroys a dynamically allocated object Calls the destructor for the objectDeallocates(i.e.,releases)memory from the free storeThe memory can then be reused by the system to allocate other objects,60,10.6 Dynamic Memory Management with Operators new and delete(Cont.),Initializing an object allocated by newInitializer for a newly created fundamental-type variableExampledouble*ptr=new double(3.14159);Specify a comma-separated list of arguments to the constructor of an objectExampleTime*timePtr=new Time(12,45,0);,61,Common Programming Error 10.8,Not releasing dynamically allocated memory when it is no longer needed can cause the system to run out of memory prematurely.This is sometimes called a“memory leak.”,62,10.6 Dynamic Memory Management with Operators new and delete(Cont.),new operator can be used to allocate arrays dynamicallyDynamically allocate a 10-element integer array:int*gradesArray=new int 10;also:int arraySize=5;/non-constint*myArray=new intarraySize;delete myArraySize of a dynamically allocated arraySpecified using any integral expression that can be evaluated at execution time,63,10.6 Dynamic Memory Management with Operators new and delete(Cont.),Delete a dynamically allocated array:delete gradesArray;This deallocates the array to which gradesArray points If the pointer points to an array of objectsFirst calls the destructor for every object in the arrayThen deallocates the memory If the statement did not include the square brackets()and gradesArray pointed to an array of objectsOnly the first object in the array would have a destructor call,64,Common Programming Error 10.9,Using delete instead of delete for arrays of objects can lead to runtime logic errors.To ensure that every object in the array receives a destructor call,always delete memory allocated as an array with operator delete.Similarly,always delete memory allocated as an individual element with operator delete;otherwise,the result of the operation is undefined.,65,10.7 static Class Members,static data memberOnly one copy of a variable shared by all objects of a class“Class-wide”information A property of the class shared by all instances,not a property of a specific object of the classDeclaration begins with keyword static,66,10.7 static Class Members(Cont.),static data member(Cont.)ExampleVideo game with Martians and other space creaturesEach Martian needs to know the martianCountmartianCount should be static class-wide dataEvery Martian can access martianCount as if it were a data member of that MartianOnly one copy of martianCount existsMay seem like global variables but they have class scopeCan be declared public,private or protected,67,10.7 static Class Members(Cont.),static data member(Cont.)Fundamental-type static data members Initialized by default to 0If you want a different initial value,a static data member can be initialized once(and only once)A const static data member of int or enum typeCan be initialized in its declaration in the class definition All other static data membersMust be defined at file scope(i.e.,outside the body of the class definition)Can be initialized only in those definitionsstatic data members of class types(i.e.,static member objects)that have default constructorsNeed not be initialized because their default constructors will be called,68,10.7 static Class Members(Cont.),static data member(Cont.)Exists even when no objects of the class existTo access a public static class member when no objects of the class existPrefix the class name and the binary scope resolution operator(:)to the name of the data member ExampleMartian:martianCountAlso accessible through any object of that classUse the objects name,the dot operator and the name of the memberExamplemyMartian.martianCount,69,10.7 static Class Members(Cont.),static member functionIs a service of the class,not of a specific object of the classstatic applied to an item at file scopeThat item becomes known only in that fileThe static members of the class need to be available from any client code that accesses the fileSo we cannot declare them static in the.cpp filewe declare them static only in the.h file.,70,Software Engineering Observation 10.11,A classs static data members and static member functions exist and can be used even if no objects of that class have been instantiated.,71,Outline,fig10_21.cpp(1 of 1),Function prototype for static member function,static data member keeps track of number of Employee objects that currently exist,72,Outline,Employee.cpp(1 of 3),static data member is defined and initialized at file scope in the.cpp file,static member function can access only static data,because the function might be called when no objects exist,73,Outline,Employee.cpp(2 of 3),Dynamically allocating char arrays,Non-static member function(i.e.,constructor)can modify the classs static data members,Deallocating memory reserved for arrays,74,Outline,Employee.cpp(3 of 3),75

    注意事项

    本文(C++教程英文版.ppt)为本站会员(牧羊曲112)主动上传,三一办公仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。 若此文所含内容侵犯了您的版权或隐私,请立即通知三一办公(点击联系客服),我们立即给予删除!

    温馨提示:如果因为网速或其他原因下载失败请重新下载,重复下载不扣分。




    备案号:宁ICP备20000045号-2

    经营许可证:宁B2-20210002

    宁公网安备 64010402000987号

    三一办公
    收起
    展开