It seems you want to overload the operator<< for a std::ostream object. I assume you're wanting to do something like so:
Rectangle rect;
std::cout << rect;
Instead of:
Rectangle rect;
std::cout << "Width: " << rect.width << '\n';
std::cout << "Height: " << rect.width;
The overloaded function (remember overloading operators is overloading functions, except with a specific signature) must have the following signature:
std::ostream& operator<<(std::ostream&, const Type& type);
Where std::ostream is an ostream
object (such as a file), in this case it will be std::cout, and Type is the type you wish to overload it for, which will be Rectangle in your case. The 2nd parameter is a const reference because printing something out doesn't usually require you to modify the object, unless I am mistaken the 2nd parameter does not have to be a const object, but it is recommended.
It must return a std::ostream in order for the following to be possible:
std::cout << "Hello " << " operator<< is returning me " << " cout so I " << " can continue to do this\n";
This is how you do so in your case:
class Rectangle{
public:
int height;
int width;
};
// the following usually goes in an implementation file (i.e. .cpp file),
// with a prototype in a header file, as any other function
std::ostream& operator<<(std::ostream& output, const Rectangle& rect)
{
return output << "width: " << rect.width <<< "\nheight: " << rect.height;
}
If you have private data in your Rectangle class, you may want to make the overloaded function a friend function. I usually do this even if I don't access the private data, just for readability purposes, it's up to you really.
i.e.
class Rectangle{
public:
int height;
int width;
// friend function
friend std::ostream& operator<<(std::ostream& output, const Rectangle& rect);
};
std::ostream& operator<<(std::ostream& output, const Rectangle& rect)
{
return output << "width: " << rect.width <<< " height: " << rect.height;
}