Making a user-defined class std::to_string(able)

前端 未结 7 1450
夕颜
夕颜 2021-02-01 02:23

I know it seems too much Java or C#. However, is it possible/good/wise to make my own class valid as an input for the function std::to_string ? Example:

<         


        
7条回答
  •  春和景丽
    2021-02-01 03:06

    You probably just want to overload operator<<() something like:

    std::ostream& operator << ( std::ostream& os, const my_class& rhs ) {
        os << "I am " << rhs.i;
        return os;
    }
    

    Alternatively:

    std::ostream& operator << ( std::ostream& os, const my_class& rhs ) {
        os << rhs.print_a_string();
        return os;
    }
    

    Then you can simply do:

    int main() {
        my_class my_object;
        std::cout << my_object;
    
        return 0;
    }
    

提交回复
热议问题