【问题标题】:Input/Output Operators Overloading in C++C++ 中的输入/输出运算符重载
【发布时间】:2020-06-01 02:21:30
【问题描述】:

陷入 ostream/istream 运算符重载 第一季度。为什么我们使用 ostream& 运算符作为朋友? Q2。为什么我们在ostream & operator << (ostream &out, const Complex &c) 中传递两个参数 Q3。为什么我们要引用 Cout 和 in ? istream & operator >> (istream &in, Complex &c).

参考:Overloading stream Oerator overloading- Geeks4Geeks

HERE IS THE CODE

#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 Imaginary Part "; 
    in >> c.imag; 
    return in; 
} 

int main() 
{ 
Complex c1; 
cin >> c1; 
cout << "The complex object is "; 
cout << c1; 
return 0; 
}

【问题讨论】:

    标签: c++ operator-overloading insertion


    【解决方案1】:

    A1。访问私有成员

    A2。第一个参数是流,第二个是对象。 operator&lt;&lt;operator&gt;&gt; 需要两个参数

    A3。因为它们在函数中被修改了。从 resp 读取的函数。写入流中。

    另外:

    • 不要使用using namespace std;
    • 不要在构造函数体中初始化成员。使用构造函数初始化列表

      Complex(int r = 0, int i =0) 
      { real = r; imag = i; } 
      

      应该是

      Complex(int r = 0, int i = 0) : real(r), imag(i) {}
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-15
      • 2012-12-30
      • 1970-01-01
      • 2021-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多