1

我得到编译器错误

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

1 回答 1

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

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

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

于 2013-11-03T10:41:59.500 回答