之前在Overloading operator <<中遇到过这个问题:无法将lvalue绑定到'std :: basic_ostream <char> &&',以下代码导致:
error: cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’
Run Code Online (Sandbox Code Playgroud)
和代码:
// tried forward declaring but this did not help
namespace Tree {
template<typename> class Node;
};
template<typename T> std::ostream& operator<<(std::ostream&, const Tree::Node<T>&);
namespace Tree {
template<typename> class Tree;
template<typename T>
class Node {
friend inline std::ostream& operator<<(std::ostream& out, const Node& node) {
return out << node.getData();
}
friend class Tree<T>;
// member declarations
...
};
template<typename T>
class Tree {
friend inline std::ostream& operator<<(std::ostream& out, const Tree& tree) {
return tree.showInOrder(out, tree.root);
}
std::ostream& showInOrder(std::ostream& out, std::unique_ptr<Node<T>> const &node) const {
if(node->left) showInOrder(out, node->left);
out << node << " "; // error: cannot bind 'std:ostream {...} to lvalue'
if(node->right) showInOrder(out, node->right);
return out;
}
};
};
Run Code Online (Sandbox Code Playgroud)
根据Bo Persson在上述链接中的回答,我对"不可导出的上下文"存在问题,但是那里接受的答案并没有解决问题.
node是一个std::unique_ptr<Node<T>>.你需要取消引用它:
out << *node << " ";
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7045 次 |
| 最近记录: |