重载提取运算符

Overloading the extraction operator

本文关键字:运算符 提取 重载      更新时间:2023-10-16

我正在重载提取运算符以读取包含一对数字的节点。

如您所见,我正在打印一条消息,让用户知道他们正在写哪个数字。但是,当我从文件中读取时,消息仍然会打印。所以我想知道是否有办法检查我是从文件还是从键盘读取,或者是否有另一种方法可以避免在我从文件读取时打印消息。

法典:

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