C++ 拷贝构造函数、移动构造函数、拷贝赋值函数、移动赋值函数
这是个类的代码,我用这个类来讲诉 C++ 拷贝构造函数、移动构造函数、拷贝赋值函数、移动赋值函数的使用。
例子:
Speaker.h:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| #pragma once #ifndef _SPEAKER_ #define _SPEAKER_
#include <string> #include <vector> using namespace std;
template<typename T> class Speaker { public: string _id; string _name; vector<T> _grade; int _final_result; Speaker() = default; Speaker(string id, string name, vector<T> grade = {}, int final_result = INT_MAX) :_id(id), _name(name), _grade(grade), _final_result(final_result) { cout << "有参构造函数:"; } Speaker(const Speaker& t) :_id(t._id), _name(t._name), _grade(t._grade), _final_result(t._final_result) { cout << "拷贝构造函数:"; } Speaker(Speaker&& t) noexcept :_id(t._id), _name(t._name), _grade(t._grade), _final_result(t._final_result) { cout << "移动构造函数:"; } Speaker& operator=(const Speaker& t) { cout << "拷贝赋值函数:"; if (this != &t) { _id = t._id; _name = t._name; _grade = t._grade; _final_result = t._final_result; } return *this; } Speaker& operator=(Speaker&& t) noexcept { cout << "移动赋值函数:"; if (this != &t) { _id = t._id; _name = t._name; _grade = t._grade; _final_result = t._final_result; } return *this; } ~Speaker() = default; };
#endif
|
main.cpp:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| #include <iostream> #include "Speaker.h" using namespace std; int main() { Speaker<double> a; Speaker<double> b("1","1"); cout << b._id << " " << b._name << endl; Speaker<double> c(b); cout << c._id << " " << c._name << endl; Speaker<double> d = b; cout << d._id << " " << d._name << endl; d = b; cout << d._id << " " << d._name << endl;
Speaker<double> e(move(b)); cout << e._id << " " << e._name << endl; Speaker<double> f = move(b); cout << f._id << " " << f._name << endl; f = move(b); cout << f._id << " " << f._name << endl;
return 0; }
|
输出:
1 2 3 4 5 6 7
| 有参构造函数:1 1 拷贝构造函数:1 1 拷贝构造函数:1 1 拷贝赋值函数:1 1 移动构造函数:1 1 移动构造函数:1 1 移动赋值函数:1 1
|