简体   繁体   中英

Overloading '<' Operator Breaks << for cout?

I have defined a Player class to do some operations with, so it is convenient for me to overload some basic operators. Specifically, I want to use < for comparisons between Player objects. As such, I have the following in the class:

bool operator<(const Player& rhs) const {return (*this < rhs );} 

Unfortunately, this has led to problems. Later, when I try to output a vector containing particular elements in my main function, the compiler lets me know that there is no match for the << operand, and it expects std::ostream << Player. Below is the line causing the issue:

vector<Player> playerVec(6);

for (int i = 0; i < 6; i++) {

cout << playerVec[i];

}

Note that I do not actually want to output any Player objects directly to stream, so I don't think I need to overload <<.

I have some idea of what is going on, in that the compiler takes my specific definition for < and then doesn't bother looking for the more general case. My question is, do I need to now overload the << operator to return its general functionality, or is there a simpler solution?

Thanks for any help provided!

I am guessing that you are dealing with two separate issues:

1) You are missing std::ostream& operator<<(std::ostream&, const Player&) , which is what you need in order to stream Player objects to std::cout and other output streams

2) You have an infinite recursion in your Player less-than comparison operator < , since the operator you provided calls itself.

I don't think, your operator<() is interfering. Depending on the complexity of your code you can verify this by simply commenting it out and check if you get the same error.

You need to specify a std::ostream & operator<<(std::ostream & os, const Player & p) non-member-function or otherwise the compiler doesn't know what to do writing something like os << myPlayer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM