【发布时间】:2020-08-24 23:46:39
【问题描述】:
头文件: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;
}
};
main() 函数:
#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 类的构造函数和析构函数调用分别是一个和一个。检查图片。
我是一个新手,所以这将是一个很大的帮助。谢谢**
【问题讨论】:
-
请将输出作为文本而不是图像复制到问题中。
标签: c++ constructor destructor copy-constructor