I have a code snippet like this:
class track {
public:
struct time {
unsigned minutes, seconds;
std::ostream& operator<<(std::ostream& o) {
o << minutes << "minute(s) " << seconds << " second(s)";
return o;
}
};
...
std::ostream& operator<<(std::ostream& o) {
o << "title: " << title << " performer: " << performer << " length: " << length << std::endl;
return o;
}
private:
std::string performer, title;
time length;
};
However, if i compile this code, i got this error:
no match for 'operator<< ...'
Could you tell me what’s wrong with this code?
If you want your object
objof classTto support typical streaming (e.g.cout << obj) you have to define an operator at global scope:(if the function needs to access private fields, you can declare it as a friend)
If, as in your code, you declare an operator as a member
you are esentially defining this:
and you can use it like this:
obj << cout, but that is probably not what you want!