没有<</>>运算符的ostream和istream重载

Sha*_*iri 0 c++ overloading comma

每当我使用coutcin时,我必须使用3键(shift,2按<<).

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

而现在一切都运作良好,除了CINint,float,double,char但它的工作原理与char[].我也测试tie()了将ostream绑定到istream的方法,但是cin流不会与cout流绑定.

事实上,cin得到了价值,但这个价值与cout无关.

非常感谢,如果你有一个想法.

#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
}
Run Code Online (Sandbox Code Playgroud)

产量

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.
Run Code Online (Sandbox Code Playgroud)

通过:g ++ 5.2.1.

如果你想测试这个代码,你的枪c ++必须是5.2或更高; 或更改()初始化为=

用于在命令行上编译

g++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp

Cod*_*ler 6

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

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

但正如graham.reeds已经说过的那样,以这种方式用逗号替换<<和>>运算符是个坏主意,它会弄乱你的代码.