65,210
社区成员
发帖
与我相关
我的任务
分享
mystream& mystream::operator<<(mystream& (__cdecl *_Pfn)(mystream&))
{
assert(NULL != _Pfn);
return (*_Pfn)(*this);
}
mystream& myend(mystream& ms)
{
ms._str = ms.str();
return ms;
}
code]
当定义了mystream自己的某种类型流运算符后,将导致继承的ostream的流运算符被隐藏!(因为stringstream中没有虚函数)。
因此,即使继承stringstream也得对<<支持的各类型进行重写。
如果想继续强制使用派生类来完成功能,那么可以对派生类的基类成分使用ostream的<<,操作如下。
[code=C/C++]
mystream mystr;
//取出基类成分
stringstream *os = &mystr;
//由于stringstream中的<<都不是虚函数,他们静态绑定在os对象,对*os的操作都是标准的ostream operator <<
*os << 5 << "abc" << 3.57;
//对mystream对象使用myend
mystr << myend;
cout << mystr<<endl;
mystream mystr;
//取出基类成分
dynamic_cast<stringstream>(mystr) << 5 << "abc" << 3.57;
//对mystream对象使用myend
mystr << myend;
cout << mystr<<endl;
ostream& operator <<(ostream& os, const mystream& ms)需要访问mystream的私有成员,因此它需要声明为mystream的友元函数。在mystream的public中添加friend ostream& operator <<(ostream&, const mystream&);
#include <iostream>
#include <sstream>
#include <cassert>
using namespace std;
class mystream
{
private:
stringstream _ss;
string _str;
public:
friend mystream& myend(mystream& ms);
friend ostream& operator <<(ostream& os, const mystream& ms);
public:
mystream& operator<< (const int& val )
{
_ss <<val;
return *this;
}
mystream& operator<< (const char* s )
{
_ss <<s;
return *this;
}
mystream& operator<< (const double& val )
{
_ss <<val;
return *this;
}
mystream& operator<<(mystream& ( __cdecl *fun)(mystream&) );
};
mystream& myend(mystream& ms)
{
ms._str = ms._ss.str();
return ms;
}
ostream& operator <<(ostream& os, const mystream& ms)
{
os<<ms._str;
return os;
}
mystream& mystream::operator<<(mystream& (*fun)(mystream&) )
{
assert(NULL != fun);
return ((*fun)(*this));
}
int main()
{
mystream mystr;
mystr << 5<< "abc" << 3.57<< myend;
cout << mystr<<endl;
return 0;
}
为什么会只提示int上有二义性呢?mystream& mystream::operator<<(mystream& (__cdecl *_Pfn)(mystream&))ostream& operator << (ostream& (__cdecl *_Pfn)(mystream&))
mystr<< 5.6 << 5<< "abc" << 3.57;
mystr << myend; //可以正确调用myend啦
mystream& operator<<(int __w64 _Val){
dynamic_cast<stringstream&>(*this) << _Val;
return *this;//返回的是基类成分!所以后面的<<可以工作了
}