How is the tostring function used in C++?

There is no built-in tostring function in C++, but a similar functionality can be achieved by custom functions or by overloading the stream insertion operator << in a class member function. For example:

#include <iostream>
#include <string>

class MyClass {
public:
    int num;
    
    MyClass(int n) : num(n) {}
    
    friend std::ostream& operator<<(std::ostream& os, const MyClass& obj) {
        os << "MyClass: " << obj.num;
        return os;
    }
};

int main() {
    MyClass obj(10);
    std::string str = obj.toString(); // 调用重载的<<运算符
    std::cout << str << std::endl;
    
    return 0;
}

In the above code, the << operator is overloaded in the MyClass class. When the object obj is passed to std::cout, the << operator is called to convert the object to a string for output.

 

More tutorials

What are the scenarios where the tostring function is used in C++?(Opens in a new browser tab)

How to Delete Elements from an Array in Java(Opens in a new browser tab)

The Command design pattern.(Opens in a new browser tab)

How is the string format used in C++?(Opens in a new browser tab)

Adding a string to a Python variable(Opens in a new browser tab)

Leave a Reply 0

Your email address will not be published. Required fields are marked *