[运算符重载]原来是这样输出的吗

该篇文章讲述了如何在C++中使用Printer类和模板函数,支持int和double等类型的数据连续输出,以及处理空括号带来的换行效果。
摘要由CSDN通过智能技术生成

描述

实现 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)('.')();
}

  • 7
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值