c 输入输出流运算符重载_学习c重载输入和输出运算符

c 输入输出流运算符重载

One of the first things you do when you are designing and implementing a class is to determine some way to get the data into your class objects and some way to get data out of your objects. Sometimes member functions work well for this, but at other times you want to use the input and output operators like you use with the built-in data types.

在设计和实现类时,要做的第一件事就是确定某种将数据放入类对象的方法以及某种将数据从对象中取出的方法。 有时成员函数可以很好地实现此目的,但有时您希望像使用内置数据类型一样使用输入和输出运算符。

In this article I’m going to show you how to overload the input operator (>>) and the output operator (<<) so that you can use them with your class objects.

在本文中,我将向您展示如何重载输入运算符( >> )和输出运算符( << ),以便可以将其与类对象一起使用。

关于运算符重载的几句话 (A Few Words about Operator Overloading)

C++ is one of the few languages to allow operator overloading. Overloading operators is useful with classes because there are times when you want to use a class object with an operator that does not recognize that object. This will be true for all your user-defined types (classes).

C ++是少数允许运算符重载的语言之一。 重载运算符对类很有用,因为有时您想将类对象与无法识别该对象的运算符一起使用。 所有用户定义的类型(类)都是如此。

For an example, consider a class called IntData. This class is a wrapper class for integers that includes (hypothetically) some functionality not found in the int type itself. If I want to add two IntData objects together, without operator overloading I will have to provide a member function for doing this. Here is an example code fragment:

例如,考虑一个名为IntData的类。 此类是整数的包装器类,该类包括(假设)包括int类型本身未提供的某些功能。 如果我想将两个IntData对象一起添加而没有操作符重载,则必须提供一个成员函数来执行此操作。 这是一个示例代码片段:

IntData d1(1);
IntData d2(2);
IntData d3 = d1.add(d2);

What I would rather do is this:

我宁愿这样做:

IntData d1(1);
IntData s2(2);
IntData d3 = d1 + d2;

I cannot do this without operator overloading because the + operator is not defined to work with my IntData objects. With operator overloading, on the other hand, I can have the + operator recognize my IntData objects and perform the resulting addition. This makes operator overloading an important part of many class definitions.

没有运算符重载,我无法做到这一点,因为+运算符未定义为与我的IntData对象一起使用。 另一方面,通过运算符重载,我可以让+运算符识别我的IntData对象并执行结果加法。 这使得运算符重载是许多类定义的重要组成部分。 <

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值