Search code examples
c++classabstract-data-type

How to return a value by class name itself in C++?


I'm working on a wrapper class for char[] in c++. Something like a String. Now I want to get a value from the object name. For example:

void main() {
    String str;
    str = "Hello";
    cout << str;
}

so the str return a character array, and cout can print it on the screen. How can I achieve this in my class? (By the way, I know there is already a string class. This is an exercise for Data Structures lesson)


Solution

  • This is probably what you mean:

    std::ostream & operator << (std::ostream & os, const String & s)
    {
        return os << s.get_char_pointer();
    }
    

    Of course you will need to change get_char_pointer to whatever works for your String.