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
对象并执行结果加法。 这使得运算符重载是许多类定义的重要组成部分。 <