【问题标题】:C++ ostream implicitly deleted with templateC++ ostream 使用模板隐式删除
【发布时间】:2013-11-28 04:39:12
【问题描述】:

我有一个模板类,我试图使用运算符

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;

我怎样才能让这个输出工作?

【问题讨论】:

  • 因为你是通过引用传递ostream,所以通过引用返回它。

标签: c++ templates pointers


【解决方案1】:

std::ostream 和兄弟姐妹没有 copy constructorscopy 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 中,它们实际上被标记为=deleted

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    • 2017-10-17
    • 1970-01-01
    相关资源
    最近更新 更多