C++: string operator overload

后端 未结 3 1205
生来不讨喜
生来不讨喜 2021-01-21 14:00

Can I overload existing function/operator in existing class?

I was trying to do:

#include 
#include 
using namespace std;

         


        
相关标签:
3条回答
  • 2021-01-21 14:12

    Use

    std::ostringstream

    #include <sstream>
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        std::ostringstream ss;
        ss << "Hello" << " " << "world";
    
        std::string s = ss.str(); 
        ss.str(std::string()); 
    
        cout << s << endl;
        return 0;
    }
    

    https://onlinegdb.com/rkanzeniI

    0 讨论(0)
  • 2021-01-21 14:31

    I defer to Benjamin's answer for creating a stream-like interface on a string object. However, you could use a stringstream instead.

    #include <sstream>
    
    std::istringstream ss;
    ss << anything_you_want;
    
    std::string s = ss.str(); // get the resulting string
    ss.str(std::string());    // clear the string buffer in the stringstream.
    

    This gives you the stream-like interface you want on a string without needing to define a new function.

    This technique can be used generally to extend the functionality of a string. That is, defining a wrapper class that provides the extended functionality, and the wrapper class also provides access to the underlying string.

    0 讨论(0)
  • 2021-01-21 14:34

    You can't add member functions to a class unless you modify that class' definition. Use a free function instead:

    string& operator<<(string & lhs, const string & rhs) {
        return lhs += rhs;
    }
    
    0 讨论(0)
提交回复
热议问题