1

I get the compiler error

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

In the main class referred to this operator overloading, but I can't undestand where the error is.

Here there is the operator overloading line, I implemented it inside the class definition.

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

vertex and priority are integer and unsigner integer.

In the main class I'm trying to doing this:

std::cout << VertexPriority(2, 3) << std::endl;
3
  • You don't define insertion operators like that, unless it is your intention to insert an ostream in to your object (which I can all-but-guarantee it is not). See the section on common operator overloading in this answer. Commented Nov 3, 2013 at 10:40
  • how should I define it? Commented Nov 3, 2013 at 10:42
  • See the linked article in my prior comment or click here Commented Nov 3, 2013 at 10:42

1 Answer 1

2

Define it like this:

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

The friend keyword is necessary if VertexPriority::vertex or VertexPriority::priority are not public.

For more help, read this tutorial: http://www.learncpp.com/cpp-tutorial/93-overloading-the-io-operators/

Sign up to request clarification or add additional context in comments.

3 Comments

ok, but now the error is [Linker error] undefined reference to `operator<<(std::ostream&, VertexPriority&)' I changed a bit your code because it doesn't let me use pointers(vp->priority) so I used the already implemented getter (vp.getVertex)
Fixed, I don't know why but I deleted a 'const' before VertexPriority in the function declaration
If you used getVertex and that was not declared const, then you would need to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.