C++实现的深拷贝
实现代码
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <queue>
#include <stack>
#include <algorithm>
#include <string>
#include <map>
#include <set>
#include <vector>
using namespace std;
class Array {
public :
Array(int n = 10) {
this->n = n;
data = new int[n];
}
Array(const Array &a) {
this->n = a.n;
this->data = new int[this->n];
for (int i = 0; i < this->n; i++) {
this->data[i] = a.data[i];
}
}
size_t size() const { return this->n; }
int &operator[](int ind) {
if (ind < 0 || ind >= n) return end;
return data[ind];
}
const int &operator[](int ind) const {
if (ind < 0 || ind >= n) return this->end;
return this->data[ind];
}
private:
int *data, end;
size_t n;
};
ostream &operator<<(ostream &out, const Array &a) {
out << "Array(" << &a << ") : ";
for (int i = 0; i < a.size(); i++) {
i && out << " ";
out << a[i];
}
return out;
}
int main() {
Array a;
for (int i = 0; i < a.size(); i++) {
a[i] = rand() %% 100;
}
cout << a << endl;
Array b = a;
cout << b << endl;
b[1] = 18432;
cout << a << endl;
cout << b << endl;
return 0;
}
- 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
- 60
- 61
- 62
- 非const和const的类型重载运算符
- 输出运算符重载
运行结果
Array(0x7ffe2145a0d0) : 83 86 77 15 93 35 86 92 49 21
Array(0x7ffe2145a0f0) : 83 86 77 15 93 35 86 92 49 21
Array(0x7ffe2145a0d0) : 83 86 77 15 93 35 86 92 49 21
Array(0x7ffe2145a0f0) : 83 18432 77 15 93 35 86 92 49 21
- 1
- 2
- 3
- 4
推荐阅读