问题遇到的现象和发生背景
为什么拷贝构造函数中必须有成员类的默认构造函数才不会报错?
问题相关代码,请勿粘贴截图
#include <iostream>
#include <string.h>
using namespace std;
class Date
{
private:
int year;
int month;
int day;
public:
//Date(){} 为什么这边一定要有个默认构造函数才不会报错?
Date(int y, int m, int d)
{
year = y;
month = m;
day = d;
}
void set(int y, int m, int d)
{
year = y;
month = m;
day = d;
}
void display()
{
cout << year << "年" << month << "月" << day << "日";
}
};
class Person
{
private:
int num;
char sex;
Date birthday;
public:
Person(int n, int y, int m, int d, char s = 'm') :birthday(y, m, d)
{
num = n;
sex = s;
}
Person(Person& p)
{
num = p.num;
sex = p.sex;
birthday = p.birthday;
cout << "调用拷贝函数" << endl;
}
void output()
{
cout << "编号:" << num << endl;
cout << "性别:" << sex << endl;
cout << "生日:";
birthday.display();
cout << endl;
}
};
int main()
{
Person p1(1,2003,7,19,'m');
p1.output();
return 0;
}
运行结果及报错内容
我的解答思路和尝试过的方法
我觉得可能是在拷贝函数建立临时对象的时候调用了 但不知道是不是
我想要达到的结果
这个默认构造函数在哪里用到了