【问题标题】:Operator overloading << error运算符重载<<错误
【发布时间】:2013-11-14 03:27:44
【问题描述】:

我得到编译器错误

no match for 'operator<<' in 'std::cout << VertexPriority(2, 4u)' 

在主类中提到了这个操作符重载,但是我想不明白错误在哪里。

这里有运算符重载行,我在类定义中实现了。

std::ostream& operator<<(std::ostream& out) const { return out << "Vertex: " << this->vertex << ", Priority: " << this->priority; }

顶点和优先级是整数和无符号整数。

在主课中我正在尝试这样做:

std::cout << VertexPriority(2, 3) << std::endl;

【问题讨论】:

  • 你不会像那样定义插入操作符,除非你打算在你的对象中插入一个 ostream(我可以保证它是 not )。请参阅常见运算符重载部分in this answer
  • 应该如何定义?
  • 查看我之前评论中的链接文章or click here

标签: c++ compiler-errors operator-overloading iostream


【解决方案1】:

这样定义:

class VertexPriority {
    ...

    friend std::ostream& operator<< (std::ostream& out, const VertexPriority& vp);
};

std::ostream& operator<< (std::ostream& out, const VertexPriority& vp) {
    return out << "Vertex: " << vp.vertex << ", Priority: " << vp.priority;
}

如果VertexPriority::vertexVertexPriority::priority 不公开,则friend 关键字是必需的。

如需更多帮助,请阅读本教程:http://www.learncpp.com/cpp-tutorial/93-overloading-the-io-operators/

【讨论】:

  • 好的,但现在错误是 [Linker error] undefined reference to `operatorpriority) 所以我使用了已经实现的getter (vp.getVertex)
  • 已修复,我不知道为什么,但我在函数声明中的 VertexPriority 之前删除了一个“const”
  • 如果你使用了getVertex,并且没有声明const,那么你需要这样做。
猜你喜欢
  • 2016-10-18
  • 1970-01-01
  • 1970-01-01
  • 2017-08-10
  • 2015-07-04
  • 1970-01-01
  • 2018-07-19
  • 1970-01-01
相关资源
最近更新 更多