Bha*_*rya 1 c++ operator-overloading
#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;
}
Run Code Online (Sandbox Code Playgroud)
将运算符作为参考“& 运算符”传递有什么用。当我们传递普通运算符时,我们从不传递引用,但在上面的代码中,我们将引用传递给运算符。任何人都可以解释传递操作员引用的部分吗?
小智 5
在代码中friend ostream & operator <<,&与重载运算符返回的类型相关联。以便它返回ostream &并istream &用于第二个。
重载运算符:
istream或ostream对象是 I/O 对象,如控制台 I/O 的 cin/cout 或其他类型的流对象(I/O from/to string 等)。返回对该对象的引用,以便您可以按顺序使用这些运算符,例如:
Complex c1
Complex c2;
cin >> c1 >> c2;
Run Code Online (Sandbox Code Playgroud)