在C++中重载输入/输出运算符

Overloading input/output operators in C++

本文关键字:输出 运算符 输入 重载 C++      更新时间:2023-10-16
#include <iostream>
using namespace std;
class Complex
{
private:
int real, imag;
public:
Complex(int r = 0, int i =0)
{  real = r;   imag = i; }
**friend ostream & operator << (ostream &out, const Complex &c);
friend istream & operator >> (istream &in,  Complex &c);**
};
ostream & operator << (ostream &out, const Complex &c)
{
out << c.real;
out << "+i" << c.imag << endl;
return out;
}
istream & operator >> (istream &in,  Complex &c)
{
cout << "Enter Real Part ";
in >> c.real;
cout << "Enter Imagenory Part ";
in >> c.imag;
return in;
}
int main()
{
Complex c1;
cin >> c1;
cout << "The complex object is ";
cout << c1;
return 0;
}

传递运算符作为参考"&运算符"有什么用。 当我们传递普通运算符时,我们永远不会传递引用,但在上面的代码中,我们将引用传递给运算符。 谁能解释传递运算符引用的部分?

在代码friend ostream & operator <<中,&与重载运算符返回的类型相关联。 以便它返回ostream &并为第二个返回istream &

重载运算符:

  1. 引用istreamostream对象,该对象是 I/O 对象,例如控制台 I/O 的 cin/cout 或其他类型的流对象(来自/到字符串的 I/O 等(。
  2. 影响对象的状态,以便读取/写入数据。
  3. 返回对该对象的引用,以便可以按顺序使用这些运算符,如下所示:

    Complex c1
    Complex c2;
    cin >> c1 >> c2;
    

通常,如果遵守每个声明声明一个名称(仅(规则, 然后,这允许在类型旁边一致地编写一个指针/引用"卡住"为:

istream& operator>> (istream& in,  Complex& c)
{ //...

通过这种方式,可以看出名为operator>>的函数正在返回一个类型istream&(对 istream 对象的引用(。

此函数采用 2 个变量:

  • istream&类型(对 istream 对象的引用(的in
  • Complex&类型(对复杂对象的引用(的c

同样适用于:

ostream& operator<< (ostream& out, const Complex& c)
{ //...

代码的格式无论如何都不会影响代码的编译方式。 所以这个答案中的函数定义与问题中的函数定义完全相同。


至于为什么要使用引用,我建议阅读:何时使用引用与指针