c++ - istream& 运算符的问题 >>

标签 c++ operators cin istream

我还在想 istream 运算符>>。 在我的函数 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() << "?";
}

最佳答案

这很好用,因为你在调用

cin >> a;

如果你这样做

ifstream ifs ("test.txt", ifstream::in);
ifs >> a;

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

正确的实现是

istream& operator >> (istream &is, Student& a)
{
    return is >> a.age;
}

现在如果你打电话

cin >> a;

它会从标准输入读取

如果你打电话

ifs >> a;

它将从文件中读取。

关于c++ - istream& 运算符的问题 >>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30221268/

相关文章:

c++ - cin std::string 带空格

c++ - 当找不到分隔符时,如何阻止 cin.getline() 导致控制台重复获取用户输入?

PHP 速记加法运算符 - undefined offset

javascript - 如何检查div元素是否为空

c++ - 在 Ubuntu 中链接 Boost.MPI 和 Boost.Serialization

c++ - 虚拟继承和参数化构造函数

JAVA基础编码。为什么100/1=110,300/3、400/4、500/5呢?

c++ - 带有转义字符的 cin.get

c++ - 错误: identifier :"SHGetKnownFolderPath" is unidentified

c++ - 为什么在 main() 中声明的指针没有改变?