题解 | #数组类的拷贝构造函数#
数组类的拷贝构造函数
https://www.nowcoder.com/practice/73014020b7d54622ac5000b06eaaa4ef
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
class Array {
private:
int n;//数组大小
int* a;//数组
public:
Array() {
cin >> n;
a = new int [n];
for (int i = 0; i < n; i++) cin >> a[i];
}
~Array() {
delete []a;
}
int getlen() {
return n;
}
int get(int i) {
return a[i];
}
// write your code here......
//因为有堆上的内存空间 所以要深拷贝
Array (const Array& another) {
//先清理旧内存 申请内存空间 然后拷贝内容
this->n = another.n;//注意要自实现拷贝的话,要将所有的东西都拷贝过来 没有拷贝这个可能出错
//因为b调用show打印的时候 拷贝对象的n是未知的 所以会访问未知的东西
this->a = new int[another.n];
for (int i = 0; i < another.n; ++i) {
(this->a)[i] = (another.a)[i];
}
}
void show() {
for (int i = 0; i < n; i++) cout << a[i] << ' ';
}
};
int main() {
Array a;
Array b = a;
b.show();
return 0;
}
查看19道真题和解析