我仍然想知道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() << "?";
}
答案 0 :(得分:5)
这样可以正常工作,因为您正在调用
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;
它会从文件中读取。
答案 1 :(得分:2)
在我的函数
package com.jfasoftware.messanger.controllers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import static org.springframework.web.bind.annotation.RequestMethod.*; @Controller public class HomePageController { @RequestMapping (value="/") public String getHome() { System.out.println("\nJSR\n"); return "home"; } }
中,我没有使用istream& operator >> (istream &is, Student& a)
但仍在函数末尾返回它。我仍然可以使用is
得到正确答案。任何人都可以解释原因吗?
由于cin >> a
正在直接访问Student::setAge()
,这与cin
恰好在您的示例中指向的流相同。
这不是正确的设计。成员设置者不应该提示用户输入。您应首先提示输入,然后将值传递给您的setter。该课程应该不知道其价值来自何处。
使用更像这样的东西:
is
答案 2 :(得分:0)
实际上你的例子中有很多要点。
首先,setter应该有一个参数。按照惯例, setter 总是会获得一个改变类的参数,然后 getter 是无参数的,应该是 const 。
其次,你的setAge实现直接访问std :: cin。如果你看一下我的例子,你会发现我确实使用了is参数。这将setAge与参数的来源分开,并允许更好的OOD。
第三,我的实现也提供了更好的抽象,因为输入流可以是任何流(例如文件,或者来自互联网的流)
#include <iostream>
using namespace std;
class Student
{
private:
int age;
public:
Student() : age(0){}
Student(int age1) : age(age1) {}
void setAge(int age1);
int getAge() const { return age; }
friend istream& operator >> (istream& is, Student& a);
};
istream& operator >> (istream &is, Student& a)
{
int age1;
is >> age1;
a.setAge(age1);
return is;
}
void Student::setAge(int age1){
age = age1;
}
int main(int argc, char* argv[])
{
Student a;
cout << "input age of the student: " << endl;
cin >> a;
cout << "Age of Student is " << a.getAge() << "?" << endl;
return 0;
}
答案 3 :(得分:0)
我没有使用
-setHidden:
是的,你做到了。你只是从不同的功能中使用它,就是全部。
它是相同的流,因为它在两种情况下都是is
。
如果您想从不同的流中提取,那么您的代码就会被破坏。这就是为什么我们更喜欢使用cin
的参数而不是猜测它是什么(operator>>
)。