ostream 和 istream 覆盖,无需 << / >> 运算符
ostream and istream overlaloading without << / >> operator
每当我使用cout和cin时,我都必须使用3键(shift,2按<<)。
我试着用,
(逗号运算符)重载ostream和istream。
现在一切都很好,除了cin在int
、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 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;
}
只是检查一下,但你知道这是你迄今为止最糟糕的想法,对吧?
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- EASTL矢量<向量<int>>连续的
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- C :对矢量进行排序&lt; struct&gt;(结构有2个整数)基于结构的整数之一
- 明确的专业化“ CheckIntmap&lt;&gt;”实例化
- 什么是模板&lt;&gt;inline bla bla
- 编辑C Qlist&lt; object*&gt; gt;QML代码和一些QML警告中的模型
- eigen :: llt&lt;eigen :: matrixxd&gt;具有不完整的类型
- 错误,包括&lt; ctype&gt;在原子上使用C 11
- std::vector<;uint8_t>;当C++11/14启用时,手动复制而不是调用memcpy
- 如何加入向量&lt; int&gt;到C 中的单个INT
- 是std :: set&lt; std :: future&gt;不可能存在
- 是numeric_limits&lt; int&gt; :: is_modulo从逻辑上矛盾
- opencv 2.4.7在iOS错误背景_segm.hpp #include&lt; list&gt;未找到
- 在修改列表后,std :: list&lt; t&gt; :: end()的值是否会更改
- ///<评论></评论>在Visual Studio中