jQuery火箭图标返回顶部代码

复制构造函数是一种特殊的构造函数,它的作用是用一个已经存在的对象去初始化另一个对象。
一般情况下不需要自行定义复制构造函数,系统默认提供一个逐个复制成员值的复制构造函数。

何时要使用呢?

1.将新对象初始化为一个同类对象
2.按值将对象传递给函数
3.函数按值返回对象
4.编译器生成临时对象

简单的样例如下:

Children.h

 1 #pragma once
 2 #include<string>
 3 using std::string;
 4 class Children
 5 {
 6 private:
 7     string Name;
 8     string Hobby;
 9     unsigned int Age;
10 public:
11     Children(const string &str1="none",const string &str2="none",unsigned int m=0);
12     virtual ~Children();
13     void show()const;
14 };

children.cpp

 1 #include "stdafx.h"
 2 #include "Children.h"
 3 #include<iostream>
 4 #include<string>
 5 using namespace std;
 6 
 7 Children::Children(const string &str1, const string &str2, unsigned int m):Name(str1),Hobby(str2),Age(m)
 8 {}
 9 
10 Children::~Children()
11 {
12 }
13 
14 void Children::show() const
15 {
16     cout << "Name: " << Name << endl;
17     cout << "Hobby: " << Hobby << endl;
18     cout << "Age: " << Age << endl;
19 }

ConsoleApplication3.cpp

 1 #include "stdafx.h"
 2 #include "Children.h"
 3 #include<iostream>
 4 #include<string>
 5 using namespace std;
 6 int main()
 7 {
 8     Children p1("XuLang", "Basketball", 24);
 9     Children p2(p1);      //这就是把Children p1的数据复制到了 Children p2;
10     Children p3 = p1;     //和上面的那个一样
11     p1.show();
12     p2.show();
13     p3.show();
14     return 0;
15 }

结果展示:

原文地址:https://www.cnblogs.com/Trojan00/p/8894141.html