How to get/set the actual value of an object
Hello, sorry for the confusing title.
Suppose I wrote a class:
1 2 3 4 5 6 7 8 9
|
class MyClass
{
std::string val;
public:
MyClass(std::string str)
{
val = str;
}
}
| |
This would allow the expression,
|
MyClass MC = "Hello, world!";
| |
correct?
But how would I make this work?
1 2
|
MyClass MC = "Hello, world!"
std::cout << MC; // How can I make this print "Hello, world!"?
| |
I hope you understand. If not, I understand.
Sorry, I confuse myself aswell.
Thanks in advance!
> How can I make this print "Hello, world!"?
Overload the stream insertion operator.
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
#include <iostream>
#include <string>
class my_class
{
std::string text ;
public:
explicit my_class( const std::string& str ) : text(str) {}
// overload the stream insertion operator
friend std::ostream& operator<< ( std::ostream& stm, const my_class& mc )
{ return stm << "my_class{ \"" << mc.text << "\" }" ; }
};
int main()
{
const my_class mc( "hello world!" ) ; // explicit constructor; so we use direct initialisation
std::cout << mc << '\n' ; // prints my_class{ "hello world!" }
}
| |
Wow, thanks! :D
Topic archived. No new replies allowed.