操作符<<'(包括string和ostream以及重载<<)

no match for 'operator<<' (with including string and ostream and overloading <<) in c++

本文关键字:ostream 重载 包括 操作符 string      更新时间:2023-10-16

我正在尝试为具有优先级的列表构建模板(模板参数为数据T和优先级Priority(例如,如果我有一排具有成绩的学生,T将是学生,他们的Priority将是他们的成绩)。该列表包含一个Node类,每个Node包含数据、优先级和指向下一个Node的指针。

我试图重载<<操作符为Node和列表,所以我可以使用<<为列表(打印每个节点)。例如:如果我想打印名为receitionhour的列表,使用这行:cout << endl << "containing: " << receptionHour << endl;

问题是编译器不能识别我实现的操作符,所以它不使用它们,并且这行不能编译。我得到的每一行的错误是:

不匹配'operator<<'(操作数类型为'std::basic_ostream'和'mtm::PriorityQueue::Node')

这里是我的<<操作符,列表(称为PriorityQueue)和节点的实现。节点(在节点类中,它在列表类中:

    template<class P, class TT>
    friend ostream& operator<<(ostream& os, Node node){
        os << "[";
        os << node.priority;
        os << ",";
        os << node.data;
        os << "]";
        return os;
    }

列表(称为PriorityQueue):

template<class P, class TT>
friend ostream& operator<<(PriorityQueue<Priority, T>& queue, std::ostream& os){
    Node* nodePtr = queue.head;
    Node node;
    for(int i = 1; i < queue.sizePQ; i++) {
        node = *nodePtr;
        os << node;
        nodePtr = node.next;
    }
    return os;
}

谢谢!

您没有正确使用模板或operator<<过载。

(1)当你声明template<class P, class TT>时,你使用这些模板的函数声明应该是function(P first, Class<TT> second)即使您的类定义(和其他函数)类似于template<class Name> Class(Name name),您也不能使用template<class T> function(Class<Name>),因为模板函数名必须与模板类名匹配。

Node的重载不需要使用模板,你知道你使用的是哪种类型(Node)。

(2)在操作符<<的重载函数中,第一个参数必须是ostream对象