老实说,我不明白你为什么想要这个,但我想这是某种锻炼或家庭作业。无论如何,实现这个功能有一些微妙之处,我怀疑你自己无法弄清楚,所以这里是可行的解决方案。
人
#include <iostream>
#include <sstream>
class Person {
public:
void process() {
// Let's see what we've got in `_request`
std::cout << _request.rdbuf() << std::endl;
// Do some processing to produce correponding _response
// In this example we hardcode the response
_response << "I'm fine, thanks!";
}
private:
std::stringstream _request;
std::stringstream _response;
// Make them all friends so that they can access `_request` and `_response`
friend Person& operator<<(Person& p, std::string const& s);
friend Person& operator<<(Person& p, std::ostream& (*f)(std::ostream&));
friend std::ostream& operator<<(std::ostream &o, Person& p);
friend Person& operator>>(Person& p, std::string& s);
};
Person& operator<<(Person& p, const std::string& s) {
p._request << s;
return p;
}
// Notice this peculiar signature, it is required to support `std::endl`
Person& operator<<(Person& p, std::ostream& (*f)(std::ostream&)) {
p._request << f;
return p;
}
// Somewhat conventional stream operator overload (in terms of signature)
std::ostream& operator<<(std::ostream &o, Person& p) {
o << p._response.rdbuf();
return o;
}
Person& operator>>(Person& p, std::string& s) {
// NOTE: This will read not the whole `_reponse` to `s`, but will stop on
// the first whitespace. This is the default behavior of `>>` operator of
// `std::stringstream`.
p._response >> s;
return p;
}
值得一提的是,就您要实现的功能而言,您的第一次尝试是完全错误的。这归结为一个事实,您似乎正在遵循有关流运算符重载的传统教程,而这里的方法应该不同以实现所需的功能。特别要注意建议的流运算符重载的签名。
此外,您必须添加更多重载以支持其他输入类型,int
例如 。本质上,您必须添加更多类似于std::basic_ostream开箱即用提供的重载。特别要注意最后一个:
basic_ostream& operator<<(basic_ostream& st,
std::basic_ostream& (*func)(std::basic_ostream&));
这家伙是来支持的std::endl
。请注意,我已经Person
为您添加了类似的重载,因此std::endl
可以正常工作(见下文)。其他重载,例如原始类型,留给您作为练习。
阅读响应
你一开始就想要的那个。
int main() {
Person daniel;
daniel << "Hello" << std::endl;
daniel << "How " << "are you";
daniel << " doing?" << std::endl;
// We are ready to process the request so do it
daniel.process();
// And Daniel's answer is...
std::cout << "Daniel says: " << daniel << std::endl;
return 0;
}
阅读回应:另一种方式
这个有点笨拙和繁琐,基本上是Person& operator>>(Person& p, std::string& s)
重载实现中注释的结果(见上文)。
int main() {
Person daniel;
daniel << "Hello" << std::endl;
daniel << "How " << "are you";
daniel << " doing?" << std::endl;
// We are ready to process the request so do it
daniel.process();
// And Daniel's answer is...
std::string part1;
std::string part2;
std::string part3;
// Will read "I'm"
daniel >> part1;
// Will read "fine,"
daniel >> part2;
// Will read "thanks!"
daniel >> part3;
std::cout << "Daniel says: " << part1 << " " << part2 << " " << part3 << std::endl;
return 0;
}