操作符<<'(包括string和ostream以及重载<<)
no match for 'operator<<' (with including string and ostream and overloading <<) in c++
我正在尝试为具有优先级的列表构建模板(模板参数为数据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
对象
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 我的运算符重载是否有效<<(流插入)左操作数不是 ostream
- oStream 不打印添加两个 valarray 的结果(使用运算符重载)
- 逗号在重载 ostream 和 istream 在结构中分开
- 重载 ostream << 运算符,指针作为参数,导致输出上的内存地址
- 从 std::ostream 重载 << 运算符时,为什么编译器会给出"too many parameters for this operator function"错误?
- 运算符的歧义错误<<自定义 std::ostream 子类中的重载
- 为什么我不能重载运算符<< 与 ostream 和 map( 或 unordered_map)?
- ostream 运算符的编译时重载
- 为什么C++在自定义结构向量时会出现 ostream 重载问题?
- 使用shared_ptr向量重载 ostream 友元运算符
- 尝试重载时'ostream'和'istream'错误C++
- 使用向量重载 ostream 运算符
- 重载运算符'<<'的使用不明确(操作数类型'ostream'(也称为"basic_ostream<char>")和"Person")
- 为什么重载运算符上的异常说明符'<<'不适用于任何 std::ostream 对象,但对库中定义的运算符不起作用?
- C++ << 使用ostream重载以正确格式化
- 打印任何带有非成员ostream重载函数的c++11数组
- ostream 重载与 for 循环,无返回值
- C++ostream重载不起作用
- 使用 OSTREAM 重载<<运算符不起作用。为什么?