我还在想 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/