istream&operator >>的问题

pex*_*a12 1 c++ operators cin istream

我仍然想知道istream operator >>.在我的函数中istream& operator >> (istream &is, Student& a),我没有使用is但仍然在函数结束时返回它.我仍然得到正确答案cin >> a.有谁能解释为什么?

#include <iostream>

using namespace std;

class Student
{
private:
    int age;
public:
    Student() : age(0){}
    Student (int age1) : age(age1) {}
    void setAge();
    int getAge(){return age;}
    friend istream& operator >> (istream& is, Student& a);
};

istream& operator >> (istream &is, Student& a)
{
    a.setAge();
    return is;
}
void Student::setAge(){
    int age1;
    cout << "input age of the student: "<< endl;
    cin >> age1;
    age = age1;
}

int main()
{
    Student a;
    cin >> a;
    cout << "Age of Student is " << a.getAge() << "?";
}
Run Code Online (Sandbox Code Playgroud)

use*_*353 5

这很好,因为你正在打电话

cin >> a;
Run Code Online (Sandbox Code Playgroud)

相反,你做了这个

ifstream ifs ("test.txt", ifstream::in);
ifs >> a;
Run Code Online (Sandbox Code Playgroud)

然后你的程序将从标准输入而不是文件(test.txt)读取,就像它应该做的那样.

正确的实施将是

istream& operator >> (istream &is, Student& a)
{
    return is >> a.age;
}
Run Code Online (Sandbox Code Playgroud)

现在,如果你打电话

cin >> a;
Run Code Online (Sandbox Code Playgroud)

它会从标准输入中读取

如果你打电话

ifs >> a;
Run Code Online (Sandbox Code Playgroud)

它会从文件中读取.