Issue
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?
Solution
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;
Answered By - Rohan Bari Answer Checked By - Marilyn (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.