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

ostream and istream overlaloading without << / >> operator

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

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

现在一切正常,除了 intfloatdoublechar 上的 cin 但它有效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
}

输出

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.

来自:g++ 5.2.1.

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

用于命令行编译

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

您的代码不适用于 int、float、double、char,因为在您的 >> 运算符中您按值而不是按引用传递参数。改成这样:

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

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

这将 'fix' 它:

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;
}

只是检查一下,但你知道这是你最糟糕的想法,对吧?