在C++中,标准库本身已经对左移运算符<<和右移运算符>>分别进行了重载,使其能够用于不同数据的输入输出,但是输入输出的对象只能是 C++ 内置的数据类型(例如 bool、int、double 等)和标准库所包含的类类型(例如 string、complex、ofstream、ifstream 等)。
如果我们自己定义了一种新的数据类型,需要用输入输出运算符去处理,那么就必须对它们进行重载。
下面以我们c++作业中的一道题为例
【CPP0048】复数类四则运算及插入/提取操作
为复数类Complex重载实现+,-,*,/,<<,>>等运算符,main(void)函数完成对其的测试
#include <iostream>
using namespace std;
#define Complex complex;
class complex {
public:
complex(double real = 0.0, double imag = 0.0) : m_real(real), m_imag(imag) { };
public:
friend complex operator+(const complex& A, const complex& B);
friend complex operator-(const complex& A, const complex& B);
friend complex operator*(const complex& A, const complex& B);
friend complex operator/(const complex& A, const complex& B);
friend istream& operator>>(istream& in, complex& A);
friend ostream& operator<<(ostream& out, complex& A);
private:
double m_real; //实部
double m_imag; //虚部
};
//重载加法运算符
complex operator+(const complex& A, const complex& B) {
complex C;
C.m_real = A.m_real + B.m_real;
C.m_imag = A.m_imag + B.m_imag;
return C;
}
//重载减法运算符
complex operator-(const complex& A, const complex& B) {
complex C;
C.m_real = A.m_real - B.m_real;
C.m_imag = A.m_imag - B.m_imag;
return C;
}
//重载乘法运算符
complex operator*(const complex& A, const complex& B) {
complex C;
C.m_real = A.m_real * B.m_real - A.m_imag * B.m_imag;
C.m_imag = A.m_imag * B.m_real + A.m_real * B.m_imag;
return C;
}
//重载除法运算符
complex operator/(const complex& A, const complex& B) {
complex C;
double square = B.m_real * B.m_real + B.m_imag * B.m_imag;
C.m_real = (A.m_real * B.m_real + A.m_imag * B.m_imag) / square;
C.m_imag = (A.m_imag * B.m_real - A.m_real * B.m_imag) / square;
return C;
}
//重载输入运算符
istream& operator>>(istream& in, complex& A) {
in >> A.m_real >> A.m_imag;
return in;
}
//重载输出运算符
ostream& operator<<(ostream& out, complex& A) {
if(A.m_imag>0)
out << A.m_real << "+" << A.m_imag << "i";
else
out << A.m_real<< A.m_imag << "i";
return out;
}
int main() {
complex c1(1, 1), c2(-1, -1), c3; //定义复数类的对象
cin >> c1;
cout << c1 << endl;
cout << c2 << endl;
c3 = c1 - c2;
cout << c3 << endl;
c3 = c1 + c2;
cout << c3 << endl;
c3 = c1 * c2;
cout << c3 << endl;
c3 = c1 / c2;
cout << c3 << endl;
return 0;
}
问题解答:
1为什么complex里面要用的友元函数?
cout 是 ostream 类的对象,cin 是 istream 类的对象,要想达到这个目标,就必须以全局函数(友元函数)的形式重载">>"和"<<",而且因为重载">>"和"<<"要用到complex的私有成员函数,所以用友元函数实现。
2为什么重载的">>"和"<<"里面的参数有istream,ostream这些东西?
ostream为输出流
&在这里为引用
ostream& out为定义一个名字为out的引用型道输出流对象
同理 in。