【发布时间】:2016-01-13 12:10:04
【问题描述】:
代码:
cout << "11122333" << endl;
期待:
11122333\n
结果:
11122333\n
好的。
代码:
cout.operator<<("11122333");
cout.operator<<(endl);
期待:
11122333\n
结果:
00B273F8\n
(或其他地址,它被转换为void* :( )
问题:
想写从ostream派生的类
class SomeStream : public ostream
{
public:
explicit SomeStream(streambuf* sb) : ostream(sb) { }
template <typename T> SomeStream &operator <<(const T &val)
{
std::ostream::operator<<(val); //Trouble in there!
std::cout << "<<" << " " << typeid(T).name() << " " << val << std::endl;
/*some other behavior*/
return *this;
}
SomeStream &operator <<(ostream& (*val) (ostream&))
{
std::ostream::operator<<(val);
/*some other behavior*/
return *this;
}
SomeStream &operator <<(ios_base& (*val) (ios_base&))
{
std::ostream::operator<<(val);
/*some other behavior*/
return *this;
}
};
当我调用父操作员std::ostream::operator<<(val); val cast 为void* 并且不能正常工作。
怎么做才对?以及为什么为ostream 直接调用operator<< 与间接调用不同。
【问题讨论】:
-
输出
operator<<()是一个全局模板函数,不是std::ostream的成员。 -
(cout.operator<<)("11122333");怎么样? -
@Kilanny - 实际上是
std::operator<<(cout, "11122333");。
标签: c++ operator-keyword ostream