没有<< ostream和istream重叠加载/>>操作者

时间:2016-04-07 10:14:15

标签: c++ overloading comma

每当我使用 cout cin 时,我必须使用3键(shift,2按<<)。

我试图用,(逗号运算符)重载ostream和istream。

现在一切正常,intfloatdoublechar上的 cin 除外,但它适用于{{1} }。我也测试了char[]方法将ostream绑定到istream,但cin流不会与cout流绑定。

实际上cin得到了值,但是这个值与cout无关。

非常感谢你的想法。

tie()

输出

#include <iostream>

using std::cout;
using std::cin;
using std::endl;


template < class AT> // AT : All Type 
std::ostream& operator,(std::ostream& out,AT t)
{
    out<<t;
    return out;
}
template < class AT> // AT : All Type 
std::istream& operator,(std::istream& in,AT t)
{
    in>>t;
    return in;
}

int main(){
    cout,"stack over flow\n";
    const char* sof ( "stack over flow\n" );
    cout,sof;

    char sof2[20] ("stack over flow\n");
    cout,sof2;

    int i (100);
    float f (1.23);
    char ch ('A');
    cout,"int i = ",i,'\t',",float f = ",f,'\t',",char ch = ",ch,'\n';
    cout,"\n_____________________\n";
    cin,sof2;  /// okay, it works
    cout,sof2; /// okay, it works
    cin,i;     /// okay it works
    cout,i;    /// does not work. does not tie to cin
}

by:g ++ 5.2.1。

如果您想测试此代码,您的枪c ++必须是5.2或更高;或者将stack over flow stack over flow stack over flow int i = 100 ,float f = 1.23 ,char ch = A _____________________ hello // cin,sof2; /// okay, it works hello 50 // cin,i; /// okay it works 100 // does not work and return the first value the smae is 100 Process returned 0 (0x0) execution time : 15.586 s Press ENTER to continue. 初始化为()

用于在命令行上编译

  

=

2 个答案:

答案 0 :(得分:6)

您的代码不适用于int,float,double,char,因为在&gt;&gt;中运算符按值传递参数,而不是通过引用传递参数。以这种方式改变它:

template < class AT> // AT : All Type 
std::istream& operator,(std::istream& in, AT& t)
{
    in>>t;
    return in;
}

但正如graham.reeds已经说过的那样,替换&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;和&gt;&gt;以这种方式使用逗号的运算符会使代码混乱。

答案 1 :(得分:1)

这将修复&#39;它:

template < class AT> // AT : All Type
std::ostream& operator,(std::ostream& out,AT&& t)
{
    out<<t;
    return out;
}
template < class AT> // AT : All Type
std::istream& operator,(std::istream& in,AT&& t)
{
    in>>t;
    return in;
}

只是检查,但你确实知道这是你最糟糕的想法,对吗?