运算符重载<<错误

时间:2013-11-03 10:38:02

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

我收到编译错误

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;

1 个答案:

答案 0 :(得分:2)

像这样定义:

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;
}

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

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