I have a class in c++, and I would like to be able to print an object, so I created a char* cast operator. The thing is that for some reason the output of the operator function is random symbols instead of my returned string. here's the code:
operator const char*()const {
std::cout << (std::to_string(Nom) + '/' + std::to_string(Denom)).c_str() << std::endl;
return (std::to_string(Nom) + '/' + std::to_string(Denom)).c_str();
}
and the main function:
Rational r1(7, 15);
std::cout << r1<<std::endl;
return 0;
The first line output normaly ("7/15"), but the return value is just random letters.
Any clues?
A complement to others answers: usually an implicit cast operator is a bad style. Especially a cast to a type that is not related with your class's one.
If you want to cast your object, the better way may be an explicit cast:
class Rational
{
public:
...
std::string toString() const
{
return std::to_string(Nom) + '/' + std::to_string(Denom);
}
};
You can overload an "out" function with it:
std::ostream & operator <<(std::ostream &stream, const Rational &obj)
{
stream << obj.toString();
return stream;
}
If you need only to out your object, you also can use an overload without cast function:
class Rational
{
public:
...
friend std::ostream & operator <<(std::ostream &stream, const Rational &obj)
{
stream << std::to_string(obj.Nom) + '/' + std::to_string(obj.Denom);
return stream;
}
};