ostream 和 istream 覆盖,无需 << / >> 运算符

ostream and istream overlaloading without << / >> operator

本文关键字:lt gt 运算符 无需 istream 覆盖 ostream      更新时间:2023-10-16

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

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

现在一切都很好,除了cinintfloatdoublechar上,但它在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 flown";
    const char* sof ( "stack over flown" );
    cout,sof;
    char sof2[20] ("stack over flown");
    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已经指出的,替换<lt;和>>运算符使用逗号,这样会把代码弄得一团糟。

这将"修复"它:

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

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