0
string var = "Hello";
cout << var << endl;

We get the result using only the object, without the help of a member variable. I want to implement a class that will work like string. For example:

class Test {
public:
    int x = 3;
};

Test var2;
cout << var2 << endl;

How can I get implement the class so the cout line prints the value of x without referring to it?

MonsterX
  • 3
  • 1
  • 3

1 Answers1

0

The std::string class has operator << overloaded, that's why when you write:

std::string text = "hello!";
std::cout << var1 << std::endl; // calling std::string's overloaded operator <<

Prints the text held by it simply.

Thus, you need to overload the << operator for the class:

class Test {
    int x = 3;
public:
    friend std::ostream& operator<<(std::ostream& out, const Test& t) {
        out << t.x;
        return out;
    }
}

// ...

Test var2;
std::cout << var2 << std::endl;
Rohan Bari
  • 7,482
  • 3
  • 14
  • 34