用c++补全下列代码int main() { array X(11,22,33,44,55,66); array Y,Z; Y.get_array(); cout<<"Display object X"<<endl; X.display(); cout<<"Display object Y"<<endl; Y.display(); Z=X+Y; cout<<"Display object Z=X+Y"<<endl; Z.display(); Z=X-Y; cout<<"Display object Z=X-Y"<<endl; Z.display(); return 0; }
时间: 2024-03-05 14:53:21 浏览: 120
C++array介绍及详细使用示例(源代码)
以下是补全代码:
```c++
#include <iostream>
using namespace std;
class array {
private:
int *arr;
int size;
public:
array() {
arr = nullptr;
size = 0;
}
array(int s) {
arr = new int[s];
size = s;
}
array(const array &obj) {
size = obj.size;
arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = obj.arr[i];
}
}
array(int a, int b, int c, int d, int e, int f) {
arr = new int[6];
arr[0] = a;
arr[1] = b;
arr[2] = c;
arr[3] = d;
arr[4] = e;
arr[5] = f;
size = 6;
}
~array() {
delete[] arr;
}
void get_array() {
cout << "Enter the size of array: ";
cin >> size;
arr = new int[size];
cout << "Enter the elements of array:" << endl;
for (int i = 0; i < size; i++) {
cin >> arr[i];
}
}
void display() {
if (size == 0) {
cout << "Array is empty" << endl;
return;
}
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
array operator+(const array &obj) {
array res(size);
for (int i = 0; i < size; i++) {
res.arr[i] = arr[i] + obj.arr[i];
}
return res;
}
array operator-(const array &obj) {
array res(size);
for (int i = 0; i < size; i++) {
res.arr[i] = arr[i] - obj.arr[i];
}
return res;
}
};
int main() {
array X(11, 22, 33, 44, 55, 66);
array Y, Z;
Y.get_array();
cout << "Display object X" << endl;
X.display();
cout << "Display object Y" << endl;
Y.display();
Z = X + Y;
cout << "Display object Z=X+Y" << endl;
Z.display();
Z = X - Y;
cout << "Display object Z=X-Y" << endl;
Z.display();
return 0;
}
```
这段代码定义了一个名为`array`的类,该类代表一个整数数组。在主函数中,首先创建了一个名为`X`的`array`对象,其构造函数接收6个整数参数。接下来创建了两个空的`array`对象`Y`和`Z`,并通过`get_array()`函数从控制台输入`Y`的元素值。然后,使用`+`和`-`运算符对`X`和`Y`进行运算,并将结果存储在`Z`中,最后分别输出`X`、`Y`和`Z`的元素值。
阅读全文