简体   繁体   中英

Stringstream - Convert an object to a string

I have a complex object that I want to be able to pass into a std::ostringstream with the << operator just like a string or int. I want to give the ostringstream the object's unique id (int) and/or name (string). Is there an operator or method I can implement in my class to allow this to work?

Define an operator overload in the same namespace as your class:

template<typename charT, typename traits>
std::basic_ostream<charT, traits> &
operator<< (std::basic_ostream<charT, traits> &lhs, Your_class const &rhs) {
    return lhs << rhs.id() << ' ' << rhs.name();
}

If the output function needs access to private members of your class then you can define it as a friend function:

class Your_class {
    int id;
    string name;

    template<typename charT, typename traits>
    friend std::basic_ostream<charT, traits> &
    operator<< (std::basic_ostream<charT, traits> &lhs, Your_class const &rhs) {
        return lhs << rhs.id << ' ' << rhs.name;
    }
};

Note that this does not result in a member function, it's just a convenient way to declare and define a friend function at once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM