为什么拷贝构造函数中必须有成员类的默认构造函数才不会报错?
#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;
}
我觉得可能是在拷贝函数建立临时对象的时候调用了 但不知道是不是
这个默认构造函数在哪里用到了
有帮助到你的话希望点个采纳支持一下博主呀
因为拷贝构造的时候程序会自动调用所拷贝类的默认构造函数,就跟创建对象一样,所以必须有默认构造函数
这是规定