任务描述 建立一个继承体系,List 是基类,ArrayList 和 LinkedList 是其派生类。并且编写实现下述函数并达到如下效果。 ostream& operator << (ostream&os, const List&rhs); 做一个流输出运算符重载,其第二个参数是List的常引用类型。我们知道子类的对象天生可以作为父类类型使用,因此 ArrayList a; LinkedList b; operator << (cout,a); operator << (cout,b); 这上面的调
时间: 2024-02-11 10:06:51 浏览: 113
用会根据对象的实际类型调用对应的重载函数,从而实现输出不同派生类的对象的功能。下面是代码示例:
```c++
#include <iostream>
#include <vector>
using namespace std;
class List {
public:
virtual void push_back(int val) = 0;
virtual int size() const = 0;
virtual int operator[](int index) const = 0;
};
class ArrayList : public List {
public:
void push_back(int val) override {
data.push_back(val);
}
int size() const override {
return data.size();
}
int operator[](int index) const override {
return data[index];
}
private:
vector<int> data;
};
class LinkedList : public List {
private:
struct Node {
int val;
Node* next;
Node(int v) : val(v), next(nullptr) {}
};
Node* head = nullptr;
int len = 0;
public:
void push_back(int val) override {
if (!head) {
head = new Node(val);
} else {
Node* cur = head;
while (cur->next) {
cur = cur->next;
}
cur->next = new Node(val);
}
++len;
}
int size() const override {
return len;
}
int operator[](int index) const override {
Node* cur = head;
while (index--) {
cur = cur->next;
}
return cur->val;
}
};
ostream& operator << (ostream& os, const List& rhs) {
int n = rhs.size();
os << "[";
for (int i = 0; i < n; ++i) {
if (i) os << ",";
os << rhs[i];
}
os << "]";
return os;
}
int main() {
ArrayList a;
a.push_back(1);
a.push_back(2);
a.push_back(3);
cout << a << endl;
LinkedList b;
b.push_back(4);
b.push_back(5);
b.push_back(6);
cout << b << endl;
return 0;
}
```
输出结果:
```
[1,2,3]
[4,5,6]
```
阅读全文