A1。访问私有成员
卡在ostream / istream运算符重载中>Q1。为什么我们使用ostream&运算符作为朋友?Q2。为什么我们在ostream & operator << (ostream &out, const Complex &c)
中传递两个参数Q3。为什么我们要引用Cout和in? istream & operator >> (istream &in, Complex &c)
。
参考:Overloading stream Oerator overloading- Geeks4Geeks
#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;
}
被ostream / istream运算符重载卡住了Q1。为什么我们使用ostream&运算符作为朋友? Q2。为什么我们要在ostream&运算符<
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) {}
A1。访问私有成员