所以基本上我只是在我的一个类方法(函数)中使用 cout/cin 用简单的代码编写了我的程序。我知道这样做不好,不应该这样做,我应该用什么来切换它们?
例如,现在我有 Human 类。它有一些字段(变量),如性别、高度、年龄。
我得到了一个叫getInfo()的方法,基本上有很多
cout << "Whats your age?" << endl;
cin >> age;
等等。我应该把它们改成什么?我应该使用类似的东西吗
ostream& operator<<(ostream &o, const Human &s)
istream& operator>>(istream &i, Human &s)
我已经写下了这些功能,但它们基本上只是用于 toString 吗?
我应该使用 toString 做什么? (需要有 toString - 我的项目的任务)。
最佳答案
您可以使 getInfo
在输入和输出流上通用,例如:
void Human::getInfo(std::istream& input, std::ostream& output) {
output << "What's your age?" << std::endl;
input >> age;
// etc.
}
toString
通常返回对象的字符串表示形式,因此它看起来像这样:
std::string Human::toString() const {
std::string string;
string += "Human(\n";
string += " age: " + std::to_string(age) + "\n";
// etc.
string += ")";
return string;
}
关于c++ - 在我的类(class)中,我应该用什么来改变 cout/cin 的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41348769/