What does "cannot convert 'this' pointer from 'const hand' to 'hand &' mean? (C++)
Question
The error occurs when I try to do this
friend std::ostream& operator<<(std::ostream& os, const hand& obj)
{
return obj.show(os, obj);
}
where hand is a class I've created, and show is
std::ostream& hand::show(std::ostream& os, const hand& obj)
{
return os<<obj.display[0]<<obj.display[1]<<obj.display[2]<<obj.display[3]<<obj.display[4];
}
where display is declared as char display[6]
.
Does anyone know what the error means?
Solution
You need to make hand::show(...)
a const
method; and it doesn't make sense to pass it obj reference -- it already receives that as the 'this
' pointer.
This should work:
class hand {
public:
std::ostream& show(std::ostream &os) const;
...
};
friend std::ostream& operator<<(std::ostream& os, const hand& obj)
{
return obj.show(os);
}
OTHER TIPS
You need the function itself to also be const (notice the "const" at the end of the first line):
std::ostream& hand::show(std::ostream& os, const hand& obj) const
{
return os<<obj.display[0]<<obj.display[1]<<obj.display[2]<<obj.display[3]<<obj.display[4];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow