我正在处理以下情况:我正在使用istringstream的operator>>在模板函数中提取格式化数据。除了使用带有空格的std::string调用函数之外,一切都运行得很好。例如std::string tmp("bla tmp");众所周知,有一个operator>> (不是istringstream的成员)接受istream和string,并使用空格作为分隔符来提取数据。所以我得到了下面的"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继承基本类型的operator>>,我从istringstream继承。但是通过实现我自己的operator>>,并通过扩展istringstream,MyClass失去了基本类型的operator>>。
发布于 2013-05-24 05:02:52
怎么会这样呢?!istringstream从istream继承基本类型的operator>>,我从istringstream继承。
您的operator >>重载会隐藏基类中的重载。您应该使用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中解释了名称隐藏的概念及其对重载解析的影响(虽然本文主要讨论虚函数,但也讨论了您所面临的完全相同的问题)。
最后,这里是使用上述更改进行编译的代码的。
https://stackoverflow.com/questions/16723802
复制相似问题