描述
实现 Printer
类,使得其对象可以通过 printer(a)(b)(c)
的方式输出 a, b, c
。需要支持以下数据类型的输出:
int
char
double
- C 风格字符串
遇到空的圆括号,则输出一个换行。
#include <iostream>
#include <cmath>
// 在此处补充你的代码
int main() {
Printer printer;
int x, y;
std::cin >> x >> y;
printer("The sum of ")(x)(" and ")(y)(" is ")(x + y)('!')();
double root = std::sqrt(x);
printer("The square root of ")(x)(" is ")(root)('.')();
}
输入
一行,两个空格分隔的整数 x 和 y。整数在 int
范围内。
输出
第一行为 "The sum of x and y is s!"
;其中 s
是 x 和 y 的和。
第二行为 "The square root of x is r."
;其中 r
是 x 的算术平方根。
输出算术类型时,使用默认的 std::ostream
设置。
样例输入
3 4
样例输出
The sum of 3 and 4 is 7! The square root of 3 is 1.73205.
解题分析
注意到有一连串的()运算符,我们考虑去重载()来达到连续输出的效果,这里我们还可以考虑在类内创建模板函数,以实现对不同类型的支持,减少代码量。
代码演示
#include <iostream>
#include <cmath>
// 在此处补充你的代码
class Printer{
public:
template<class T>
Printer& operator()(T c){
std::cout<<c;
return *this;
}
Printer& operator()(){
std::cout<<std::endl;
return *this;
}
};
int main() {
Printer printer;
int x, y;
std::cin >> x >> y;
printer("The sum of ")(x)(" and ")(y)(" is ")(x + y)('!')();
double root = std::sqrt(x);
printer("The square root of ")(x)(" is ")(root)('.')();
}