首页 > 技术文章 > 复制构造函数复制属性为某类类型的对象

abtious 2020-04-27 16:00 原文

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 /*
 5 类中含有属性是某类类型的对象
 6 复制构造函数中的(原类中的属性为某类的对象)赋值给(现在类中的某类的对象)是调用哪个函数(使用重写赋值运算符还是复制构造函数)
 7 结论是使用重写运算符
 8 */
 9 
10 class Date{
11 private:
12     int year;
13     int month;
14     int day;
15 public:
16     Date(){}//默认构造函数
17     Date(int year, int month, int day);
18     ~Date();
19     Date(Date&date);
20     void setDate(int year,int month,int day);
21     void printDate();
22     Date& operator =(const Date &date);
23 
24 };
25 Date::Date(int year, int month, int day) :year(year), month(month), day(day){
26     cout << "date构造函数"<<endl;
27 }
28 Date::~Date(){}
29 void Date::setDate(int year, int month, int day){
30     this->year = year;
31     this->month = month;
32     this->day = day;
33 }
34 void Date::printDate(){
35     cout << "日期是:" << year << "" << month << "" << day << "";
36 }
37 Date::Date(Date&date){
38     
39     year = date.year;
40     month = date.month;
41     day = date.day;
42     cout << "调用了date的复制构造函数"<<endl;
43 }
44 
45 Date& Date::operator =(const Date &date){
46     this->year = date.year;
47     this->month = date.month;
48     this->day = date.day;
49     cout << "哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈调用了赋值运算符" << endl;
50     return *this;
51 }
52 
53 
54 
55 class People{
56 private:
57     string number;
58     char sex;
59     Date birthday;
60     string id;
61 public:
62     People(string number,char sex,Date birthday,string id);//构造函数
63     People(People&people);//复制构造函数
64     ~People();//析构函数
65 
66 
67 };
68 
69 People::People(string number, char sex, Date birthday, string id) :number(number), sex(sex), birthday(birthday), id(id){
70     cout << "调用People的构造函数完毕!"<<endl;
71     /*
72     调用两次Date的复制构造函数是因为,先赋值给形参,然后形参赋值给对象属性
73     */
74 }
75 People::People(People&people){
76     number = people.number;
77     sex = people.sex;
78     birthday = people.birthday;//调用的是哪个函数、、、、、、、、、
79     id = people.id;
80     cout << "调用People的复制构造函数完毕"<<endl;
81 }
82 People::~People(){}
83 
84 int main(){
85     Date date1(2020,4,20);
86     People peo("101",'m',date1,"320721");
87     People peo2= peo;//调用复制构造函数,其中Date类的对象复制调用重写的赋值运算符
88     return 0;
89 }

 

 

结论:调用重写的赋值运算符

推荐阅读