2011-08-13 53 views
3

我正在学习流媒体。标准流提供<<操作者可以声明为:为什么输出运算符'os << value'而不是'value >> os'?

ostream& operator<<(stream& os, CLASS& rc); 

为何不能将其声明为这个?

ostream& operator>>(CLASS& rc, stream& os); 

然后,我也许可以这样做:

rc.something >> os; 

作为其实现的一部分。


编辑的人帮助我了解更多关于这一点,我很感谢。

但是我坚持如何实现它。

我已经试过

ostream& operator >> (const SomeClass& refToCls, stream& os) 
{ 
    refToCls.iVar >> os; 
    return os; 
} 

,但它失败。我该如何解决它?

+3

注意,你应该使用'CLASS常量与rc'。 –

+0

你也指istream在使用时>>不是吗? –

+0

@Martin,感谢您的加入,请看这个答案,并为我提供一个实现>>,使得这种链接工作,如果可能的话。 – Dalton

回答

7

事实上,它是可能的定义

ostream& operator>>(CLASS& rc, ostream& os); 

但你必须链这样的:

a >> (b >> (c >> str)); 

>>运算符是左结合的,所以默认此:

a >> b >> c >> str; 

相当于:

((a >> b) >> c) >> str; 

它有一个错误的含义。

+7

+1:确实。它当然是可以完成的;这很愚蠢。 –

+0

谢谢ybungalabill, – Dalton

+0

@Tomalak,为什么这样呢? – Dalton

1

这里是你如何能做到这一点,而不必担心关联性,具有辅助类来收集输入,然后将其发送到ostream的:

#include <iostream> 
#include <string> 
#include <sstream> 
#include <algorithm> 

class ReversePrinter 
{ 
    std::string acc; 
public: 
    template <class T> 
    ReversePrinter(const T& value) 
    { 
     *this >> value; 
    } 

    template <class T> 
    ReversePrinter& operator>>(const T& value) 
    { 
     std::stringstream ss; 
     ss << value; 
     acc += ss.str(); 
     return *this; 
    } 
    std::ostream& operator>>(std::ostream& os) 
    { 
     std::reverse(acc.begin(), acc.end()); 
     return os << acc; 
    } 
}; 

struct R 
{ 
    template <class T> 
    ReversePrinter operator>>(const T& value) { 
     return ReversePrinter(value); 
    } 
}; 

int main() 
{ 
    std::string name = "Ben"; 
    int age = 14; 
    const char* hobby = "reading backwards"; 
    R() >> "Hello, my name is " >> name >> "\nI'm " 
     >> age >> " years old and I like " >> hobby >> std::cout; 
} 
+0

难道你不想'acc = ss.str()+ acc;'然后跳过'std :: reverse'?否则,它不会将所有单词向后打印出来吗? –

相关问题