C++: string operator overload

时光总嘲笑我的痴心妄想 提交于 2019-12-20 02:55:09

问题


Can I overload existing function/operator in existing class?

I was trying to do:

#include <iostream>
#include <string>
using namespace std;

string& string::operator<<(const string& str) {
  this->append(str);
}

But this gives me error:

test.cpp:5: error: too few template-parameter-lists

How can I do this? Or I can't?


回答1:


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;
}



回答2:


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.



来源:https://stackoverflow.com/questions/11515925/c-string-operator-overload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!