我有一个模板化的类,我试图使用operator<<但得到错误:
Vertex.h:24:16: error: use of deleted function 'std::basic_ostream<char>::basic_ostream(const std::basic_ostream<char>&)'
其中第24行引用以下代码中的输出运算符的返回:
/In declaration of templated class Vertex
friend std::ostream operator<<(std::ostream& ost, const Vertex<T>& v) {
ost << v.getItem();
return ost;
}
//In main function
Vertex<int>* v1 = new Vertex<int>();
v1->setItem(15);
cout << *v1 << endl;
如何使此输出有效?
答案 0 :(得分:9)
std::ostream
和兄弟姐妹没有copy constructors和copy assignment operators [1] ,当您制作以下可能错误的代码时
std::ostream operator<<(std::ostream& ost, const Vertex<T>& v) {
// ^ Returning by value
ost << v.getItem();
return ost;
}
您实际上是在尝试返回ost
的副本。要解决此问题,您必须通过引用返回流。
std::ostream& operator<<(std::ostream& ost, const Vertex<T>& v) {
// ^ This
[1] 在C ++ 11中,它们实际上标记为=delete
d