Input/Output C++ 中的运算符重载
Input/Output Operators Overloading in C++
卡在 ostream/istream 运算符重载
Q1。为什么我们使用 ostream& operator 作为朋友?
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;
}
A1。访问私有成员
A2。第一个参数是流,第二个是对象。 operator<<
和 operator>>
需要两个参数
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) {}
卡在 ostream/istream 运算符重载
Q1。为什么我们使用 ostream& operator 作为朋友?
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;
}
A1。访问私有成员
A2。第一个参数是流,第二个是对象。 operator<<
和 operator>>
需要两个参数
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) {}