vector 拷贝一段
时间: 2023-09-30 15:05:43 浏览: 88
截取一个文件的一段内容
vector类的定义如下:
```c++
class vector {
private:
int* data;
int size;
public:
vector(int n) {
data = new int[n];
size = n;
}
~vector() {
delete[] data;
}
// 拷贝构造函数
vector(const vector& other) {
size = other.size;
data = new int[size];
for (int i = 0; i < size; i++) {
data[i] = other.data[i];
}
}
};
```
已知一个对象`vector a(10)`,实现`vector b(a)`的拷贝,可以直接使用拷贝构造函数:
```c++
vector b(a);
```
完善程序如下:
```c++
#include <iostream>
using namespace std;
class vector {
private:
int* data;
int size;
public:
vector(int n) {
data = new int[n];
size = n;
}
~vector() {
delete[] data;
}
// 拷贝构造函数
vector(const vector& other) {
size = other.size;
data = new int[size];
for (int i = 0; i < size; i++) {
data[i] = other.data[i];
}
}
};
int main() {
vector a(10);
vector b(a);
return 0;
}
```
阅读全文