第2关:普通非成员函数的动态绑定 建立一个继承体系,List 是基类,ArrayList 和 LinkedList 是其派生类。并且编写实现下述函数并达到如下效果。 ostream& operator << (ostream&os, const List&rhs); 做一个流输出运算符重载,其第二个参数是List的常引用类型。我们知道子类的对象天生可以作为父类类型使用,因此 ArrayList a; LinkedList b; operator << (cout,a); operator << (c
时间: 2023-12-03 07:47:08 浏览: 184
out,b); 都应该是合法的,并且输出各自的列表元素。
以下是实现代码:
```cpp
#include <iostream>
#include <vector>
using namespace std;
class List {
public:
virtual void print(ostream& os) const = 0;
};
class ArrayList : public List {
public:
ArrayList() {}
void print(ostream& os) const override {
for (auto i : data) os << i << " ";
}
private:
vector<int> data = {1, 2, 3, 4, 5};
};
class LinkedList : public List {
public:
LinkedList() {}
void print(ostream& os) const override {
for (auto i : data) os << i << " ";
}
private:
vector<int> data = {6, 7, 8, 9, 10};
};
ostream& operator << (ostream& os, const List& rhs) {
rhs.print(os);
return os;
}
int main() {
ArrayList a;
LinkedList b;
cout << a << endl;
cout << b << endl;
return 0;
}
```
输出结果为:
```
1 2 3 4 5
6 7 8 9 10
```
阅读全文
相关推荐


















