运算符重载
一元运算符*
二元运算符+ - = && || << >>
三元运算符 :?
#include<string.h>
#include<iostream>
using namespace std;
class Complex
{
public:
Complex(int a, int b)
{
_a = a;
_b = b;
}
Complex operator+(const Complex& src)const
{
int a = _a + src._a;
int b = _b + src._b;
return Complex(a, b);
}
Complex operator-(const Complex& src)const
{
int a = _a - src._a;
int b = _b - src._b;
return Complex(a, b);
}
bool operator&&(const Complex& src)const
{
return (_a && src._a);
}
void operator<<(ostream& out)//调用从c1.operator<<(cout);
{
out << _a << "+"<<_b<<endl;
}
friend ostream& operator<<(ostream& out, const Complex& src);
friend istream& operator>>(istream& in, Complex& src);
Complex& operator++()//前置++
{
++_a;
return *this;
}
Complex operator++(int)
{
int tmp = _a;
_a++;
return Complex(tmp, _b);
}
private:
int _a;
int _b;
};
ostream& operator<<(ostream& out, const Complex& src)//调用cout<<c1;
{
out<< src._a << "+" <<src. _b << endl;
return out;
}
istream& operator>>(istream& in, Complex& src)
{
in >> src._a;
in >> src._b;
return in;
}
int main()
{
string s1 = "aaaaaaa";
string s2 = "bbbbbb";
string s3 = s1 + s2;
cout << s3 << endl;
Complex c1(1, 2);
Complex c2(2, 3);
Complex c3 = c1+c2;//调用
ostream& out = cout;
istream& in = cin;
if (c1 && c2)
{
cout << "all 0" << endl;
}
return 0;
}
输出流是ostream,输入流是istream,这也是两个类,并且只能有一个对象,因此在定义in和out时必须得加&(引用)。
输入输出流有两种方法,第一种调用不方便,是根据对象在调用,因为在类内有一个this指针,所以调用依赖对象,除了代码中方法调用,还可以用c1<<out,out带不带括号都可以,第二种是在类外实现无this指针,因此可以用简便的方法调用,out<<c1;当返回值是ostream的引用时还可以连着输出。但是得在类中声明该函数是他的朋友。