【发布时间】:2021-05-07 23:12:22
【问题描述】:
我对 C++ 中的模板非常陌生,目前我在理解它们时遇到了一些麻烦。所以,有人给了我下一个使用模板的链表实现,而运算符重载对我来说非常不清楚。代码如下:
#include <iostream>
using namespace std;
template<typename T> class List;
template <typename T>
ostream& operator<< (ostream&, const List<T>&);
template <typename T>
struct Node {
T info;
Node<T>* next;
Node (T x, Node<T>* n = nullptr) : info(x), next(n) {}
};
template <typename T>
class List {
Node<T>* first, *last;
public:
List() {
this->first = nullptr;
this->last = nullptr;
}
List (initializer_list<T> l)
{
...
}
~List();
template <typename U>
friend istream& operator >>(istream& is, List<U>& l); /// ***HERE***
friend ostream& operator<< <T> (ostream&, const List<T>&); /// ***HERE***
void insert(T,unsigned);
};
template <typename T> List <T>::~List()
{
...
}
template <typename T>
istream& operator >>(istream& is, List<T>& l)
{
Node<T>* f = l.first;
while (f != nullptr)
{
is >> f->info;
f = f->next;
}
return is;
}
template <typename T>
ostream& operator<< (ostream& out, const List<T>& l) {
Node<T>* p = l.first;
while (p != nullptr) {
out << p->info << " ";
p = p->next;
}
return out;
}
template<typename T>
void List<T>::insert(T t, unsigned x)
{
...
}
int main () {
}
他为什么使用template <typename U> 来重载>> 和friend ostream& operator<< <T> (我什至不知道<T> 右边的<T> 是什么意思)。
【问题讨论】:
-
ostream& operator<< <T> (ostream&, const List<T>&);是上面声明的模板的实例化。类似于拥有template <typename T> void foo();,然后是foo<T>();。为什么作者不为operator>>做同样的事情不清楚,你要问作者。 -
你需要好好学习一下C++编程语言的参考书。你可以从:cplusplus.com/doc/oldtutorial/templates
标签: c++ templates linked-list operator-overloading