I am making a simple class that uses operator<< . It will store two parallel data arrays, each with a different (but already known) data type. The idea is that the final interface will look something like this:
MyInstance << "First text" << 1 << "Second text" << 2 << "Third text" << 3;
To make arrays look something like this:
StringArray: | "First text" | "Second text" | "Third text" | IntArray: | 1 | 2 | 3 |
I can process the input validation logic to make sure everything matches, but I'm confused by the technical details of operator<< .
The tutorials I checked say to overload it as a friend function with the return type std::ostream& , but my class has nothing to do with streams. I tried using void as the return type, but got compilation errors. In the end, I ended up returning a class reference, but I'm not sure why this works.
Here is my code:
class MyClass { public: MyClass& operator<<(std::string StringData) { std::cout << "In string operator<< with " << StringData << "." << std::endl; return *this; // Why am I returning a reference to the class...? } MyClass& operator<<(int IntData) { std::cout << "In int operator<< with " << IntData << "." << std::endl; return *this; } }; int main() { MyClass MyInstance; MyInstance << "First text" << 1 << "Second text" << 2 << "Third text" << 3; return 0; }
Additionally, a user of my class might do something like this, which is undesirable:
MyInstance << "First text" << 1 << 2 << "Second text" << "Third text" << 3;
What can I do to alternate the nature of the input?
source share