How to convert an object to a string?
So let's say that we have a class called Date for example. And you want to convert an object of a date to a string, so you can do this:
1 2 3
|
Date holiday;
std::cout << holiday;
| |
Here's my code inside the Date class:
1 2 3 4 5 6 7 8
|
operator string () // converts objects into strings
{
dateInString += to_string(month) + " / ";
dateInString += to_string(day) + " / ";
dateInString += to_string(year) + " / ";
return dateInString;
}
| |
But this isn't working. How do I fix this?
Last edited on
You need to say
|
std::cout << std::string(holiday);
| |
Or overload operator<<, too:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
#include <iostream>
#include <string>
struct Date
{
int year, month, day;
Date(int y, int m, int d) : year{y}, month{m}, day{d} {}
operator std::string() const
{
return std::to_string(month) + " / "
+ std::to_string(day) + " / "
+ std::to_string(year);
}
};
std::ostream& operator<<(std::ostream& out, const Date& d)
{
return out << std::string(d);
}
int main()
{
Date holiday(1997, 2, 13);
// Not using operator<< overload
std::cout << std::string(holiday) << '\n';
// Using operator<< overload
std::cout << holiday << '\n';
}
| |
Last edited on
But this isn't working. How do I fix this? |
In your particular code example, you seem to be trying to use the variable
dateInString without creating it. You can't use variables that don't exist.
Topic archived. No new replies allowed.