【发布时间】:2015-07-25 02:54:35
【问题描述】:
我仍然想知道 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() << "?";
}
【问题讨论】:
-
问问自己
is参数对你的操作员有什么意义,如果你只是要在setAge中点击cin?setAge应该这样做:采用int参数并设置age成员。留下你如何获得传递的价值。