(1) 定义类MyList,实现列表中每个元素加、减、乘、除n,并返回列表长度并输出列表。参照重载运算符"+"将其他重载运算符代码补全并测试:
时间: 2024-05-04 22:20:39 浏览: 76
用c++实现Money类的“+”、“-”、“==”以及“<<” 、“ >>”的运算符重载,并设计测试程序
5星 · 资源好评率100%
下面是MyList类的实现代码:
```cpp
#include <iostream>
#include <vector>
using namespace std;
class MyList {
public:
MyList(vector<int> v) : data(v) {}
// 加法运算符重载
MyList operator+(const MyList& other) const {
vector<int> result;
for (int i = 0; i < data.size(); i++) {
result.push_back(data[i] + other.data[i]);
}
return MyList(result);
}
// 减法运算符重载
MyList operator-(const MyList& other) const {
vector<int> result;
for (int i = 0; i < data.size(); i++) {
result.push_back(data[i] - other.data[i]);
}
return MyList(result);
}
// 乘法运算符重载
MyList operator*(int n) const {
vector<int> result;
for (int i = 0; i < data.size(); i++) {
result.push_back(data[i] * n);
}
return MyList(result);
}
// 除法运算符重载
MyList operator/(int n) const {
vector<int> result;
for (int i = 0; i < data.size(); i++) {
result.push_back(data[i] / n);
}
return MyList(result);
}
int length() const {
return data.size();
}
void print() const {
for (int i = 0; i < data.size(); i++) {
cout << data[i] << " ";
}
cout << endl;
}
private:
vector<int> data;
};
```
下面是测试代码:
```cpp
int main() {
vector<int> v1 = {1, 2, 3};
vector<int> v2 = {4, 5, 6};
MyList list1(v1);
MyList list2(v2);
MyList list3 = list1 + list2;
list3.print(); // 输出:5 7 9
MyList list4 = list2 - list1;
list4.print(); // 输出:3 3 3
MyList list5 = list1 * 2;
list5.print(); // 输出:2 4 6
MyList list6 = list2 / 2;
list6.print(); // 输出:2 2 3
cout << "List1 length: " << list1.length() << endl; // 输出:List1 length: 3
return 0;
}
```
阅读全文