2016-01-13 66 views
0

代码:
ostream的运营商<<调用父ostream的

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*而不是正常工作。 如何正确做?以及为什么直接致电operator<<ostream与间接呼叫不一样。

+0

输出'运营商<<()'是一个全球性的模板函数不'的std :: ostream'的成员。 –

+0

'(cout.operator <<)(“11122333”);'? – 2016-01-13 12:36:07

+1

@Kilanny - 它实际上是'std :: operator <<(cout,“11122333”);'。 –

回答

3

输出operator <<对于const char*不是ostream类型的成员。 Only those重载是成员函数,其中之一是void*。 也有non-member overloads

有解决方法:

template <typename T> SomeStream &operator <<(const T &val) 
    { 
    static_cast<std::ostream&>(*this) << val; //Trouble in there! 
    std::cout << "<<" << " " << typeid(T).name() << " " << val << std::endl; 
    /*some other behavior*/ 
    return *this; 
    } 
+0

只有'static_cast (* this)<< val;' ->工作。 'static_cast (* this)<< val;' ->不工作 - >错误C2248:'std :: basic_ostream <_Elem,_Traits> :: basic_ostream':无法访问类 – Jesus05

+0

@ Jesus05中声明的私有成员当然,对不起,只是印刷错误。 – ForEveR

+0

非常感谢您的决定。我很高兴:) – Jesus05