软件设计(II)教学课件:Chapter6 Constructors and Destructors.pptVIP

  • 0
  • 0
  • 约8.47千字
  • 约 25页
  • 2021-11-30 发布于安徽
  • 举报

软件设计(II)教学课件:Chapter6 Constructors and Destructors.ppt

Deep Copy -- Customized Copy Constructor Explicitly define copy constructor Allocate new memory for pointers to point * Person::Person(Person person) { id = person.id; Date *p = person.getBirthDate(); birthDate = new Date(*p); } Run CustomCopyConstructor Person1 .h Person1.cpp §6.5 Destructors Invoked to destroy an object The opposite of constructor Like “new” vs. “delete” Named as “~ClassName” * Run TestCircle6.cpp Circle6.h Circle6.cpp ~Circle() { numberOfObjects--; } Notes No return value, no parameters So, no overloading A default destructor is available if No destructor is explicitly defined A destructor is useful if some resource, e.g. memory is allocated dynamically by an object * Person::Person(int id, int year, int month, int day) { this - id = id; birthDate = new Date(year, month, day); } Person::~Person() { delete birthDate; } Summary Constructors to initialize object Initialize object and allocate memory Special characteristics Overloading Copy constructor Shallow copy vs. deep copy Const object for non-modify Destructor to destroy objects * Review Questions Q6.1 Q6.9 * Chapter 6 Constructors and Destructors 构造函数与析构函数 §6.1 Basic Constructors §6.2 Dynamic Initialization of Objects §6.3 Dynamic Constructors §6.4 Copy Constructors §6.5 Destructors * §6.1 Simple Constructors A special member function to construct objects Plays the role of initializing objects Exactly the same name as the class Executed automatically by the system, NOT YOU! class integer{ private: int m,n; public: integer( ); }; integer:: integer( ){ m=0; n=0; } int main(){ integer i; } Constructor is Special Should be declared in pubic section No return type, not even “void” Make ‘implicit calls’ to the operators new and delete when memory allocation is required. Can’t refer their addresses An object with a constructor (or destructor) can’t be used as a member of a union * * Default Constructor A special constructor No paramet

文档评论(0)

1亿VIP精品文档

相关文档