首页 > 解决方案 > 在 C++ 中重载输入/输出运算符

问题描述

#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;
}

将运算符作为参考“& 运算符”传递有什么用。当我们传递一个普通的操作符时,我们从不传递引用,但是在上面的代码中,我们将引用传递给了操作符。谁能解释传递操作员参考的部分?

标签: c++operator-overloading

解决方案


在代码friend ostream & operator <<&,与重载运算符返回的类型相关联。这样它就会返回ostream &并返回istream &第二个。

重载的运算符:

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

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

推荐阅读