我正在处理以下情况: 我正在使用 istringstream 的运算符 >> 在模板函数中提取格式化数据。 除了使用有空间的 std::string 调用函数时,一切都很好。 例如std::string tmp("bla tmp"); 众所周知,有一个运算符>>(不是 istringstream 的成员),它接受 istream 和字符串并使用空格作为分隔符提取数据。 所以我得到以下“bla”而不是“bla tmp”。 简而言之,我尝试变得成熟并做了以下事情:
class MyClass : public istringstream{
public:
MyClass(const char* st) : istringstream(st){}
void operator>>(string& st){st = this->str();}
}
但现在我面临这个问题:
MyClass my("bla tmp");
string tmp;
my >> tmp; // now tmp == "bla temp" and this is exactly what I wanted
//but this does not work
int kk;
my >> kk; //gives me "no match for operator>>"
怎么可能?! istringstream 从 istream 继承基本类型的运算符>>,而我从 istringstream 继承。 但是通过实现我自己的运算符>>并通过扩展 istringstream 结果 MyClass 失去了基本类型的运算符>>。
最佳答案
How can it be ?! istringstream inherits operator>> for basic type from istream and I inherit from istringstream.
您的运算符>>
重载隐藏了基类中的运算符。您应该使用 using
声明来使基类中的 operator >>
重载参与重载决策:
class MyClass : public std::istringstream {
public:
using std::istringstream::operator >>;
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
MyClass(const char* st) : std::istringstream(st){}
void operator>>(std::string& st){st = this->str();}
};
名称隐藏的概念及其如何干扰重载解析在 this article by Herb Sutter 中进行了解释。 (虽然本文主要是关于虚拟函数的,但它确实讨论了您面临的完全相同的问题)。
最后,这是一个live example使用上述更改编译的代码。
关于c++ - 派生 istringstream 并实现运算符>>(string&),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16723802/