头文件:Date.h文件
#include<iostream>
#include<cstdlib>
#include<cstring>
using namespace std;
class Date{
private:
int day;
int month;
int year;
public:
Date(int d = 1, int m = 1, int y = 1900): day(d), month(m), year(y)
{
cout << "date constructor is called"<< endl;
}
void print() const {
cout << day << ":" << month << ":" << year <<endl;
}
~Date(){
cout << "date destructor is called"<< endl;
}
};
头文件:Employee.h
#include"Date.h"
class Employee{
private:
char *fname;
char *lname;
Date dob; // object, has-a relationship
Date hiredate; // object, has-a relationship
public:
Employee(char *f, char *l, Date bd, Date hd){
cout << "employee constructor is called"<< endl;
int lengthf;
lengthf = strlen(f);
fname = new char[lengthf+1];
strcpy(fname, f);
int lengthl;
lengthl = strlen(l);
lname = new char[lengthl +1];
strcpy(lname, l);
}
~Employee(){
delete [] fname;
delete [] lname;
cout << "employee destructor is called"<< endl;
}
};
主功能:
#include"Employee.h"
int main(){
Date db(07, 11, 1991);
Date dh;
dh.print();
Employee e("Dan", "Lee", db , dh);
db.print();
system("pause");
return 0;
}
因此,问题是,正如我们所看到的,有4个日期构造函数正在执行,然后有Employee类构造函数正在被调用。接下来,将执行两个日期析构函数。现在,当我们获得“按下键”选项时,一旦按下,我们将在另外4个日期析构函数调用之前接到Employee析构函数的调用。因此,总共有4个日期构造函数调用,而6个日期构造函数调用。但是,Employee类调用一个构造函数和析构函数。
**为什么会有4个日期构造函数调用和更多的析构函数调用,6个析构函数调用?此外,任何人都可以一一详述这些序列并指定调用这些构造函数和析构函数的点。
此外,需要注意的是,成员对象通过值传递给Employee构造函数。但是,如果通过引用传递,那么将有4个日期构造函数调用和4个日期析构函数调用,而Employee类有一个和一个构造函数和析构函数调用。检查图片。
我是新手,因此会很有帮助。谢谢 **
The two additional destructor calls are generated by the
Date
objects generated by the implicit copy constructors when passed by value to theEmployee
class constructor. These two newDate
objects are destroyed as soon as theEmployee
constructor finishes.