重载提取运算符
Overloading the extraction operator
我正在重载提取运算符以读取包含一对数字的节点。
如您所见,我正在打印一条消息,让用户知道他们正在写哪个数字。但是,当我从文件中读取时,消息仍然会打印。所以我想知道是否有办法检查我是从文件还是从键盘读取,或者是否有另一种方法可以避免在我从文件读取时打印消息。
法典:
istream &operator>>( istream &input, nod &X )
{
cout<<"Number 1: ";
input>>X.info1;
cout<<"Number 2 ";
input>>X.info2;
X.next=NULL;
return input;
}
根本不应在流式处理运算符中与用户交互。
这不是它们的用途,operator>>
应该只读取流中的下一个对象。
相反,先交互,然后构造对象:
nod read_nod()
{
int info1 = 0;
cout << "Number 1: ";
cin >> info1;
int info2 = 0;
cout << "Number 2: ";
cin >> info2;
return nod(info1, info2);
}
或
istream & operator>> (istream &input, nod &X)
{
input >> X.info1;
input >> X.info2;
X.next = NULL;
return input;
}
nod read_nod()
{
cout << "Enter two numbers for the nod: ";
nod n;
cin >> n;
return n;
}
相关文章:
- 在C++中使用重载提取运算符时出现问题
- 使用 istream 提取运算符进行 csv 解析:如何检测缺失的字段值?
- 调用提取重加载器会产生对"运算符"的未定义引用错误>>
- 将文本文件数据读入字符数组时提取运算符的歧义
- 派生类 插入和提取运算符重载以及基类与派生类之间的强制转换
- 长方程加法/减法计算器,从文本文件中提取运算符和数字
- 运算符重载流提取运算符 (>>) C++会导致无限递归流提取
- 无法在C++中过载流提取运算符 (>>)
- 带有指针的重载插入/提取运算符
- 防止为字符串流提取运算符不支持的类型实例化模板类 (>>)
- 为什么我不能对提取运算符进行 decltype
- 编译器在遇到提取或插入运算符时处理信息(字符串、操纵器等)的顺序是什么?
- 是否保证标准提取运算符>>在失败时不会更改参数?
- 提取运算符 (>>) 可以覆盖变量吗?
- 重载提取运算符
- C++ 重载提取运算符 - 无法访问类中声明的私有成员
- 如何在重载提取运算符中读取行(忽略空格字符)
- 重载提取和插入运算符 C++
- 将一个向量(从向量的一个向量中提取)分配给另一个向量时出错,运算符为
- 如何在C++中重载模板的朋友提取运算符(>>)?