操作符重载的两种用法(前置后置++)

来源:互联网 发布:js 全等 编辑:程序博客网 时间:2024/05/31 05:27

一.操作符重载基础:

运算符函数是一种特殊的成员函数或友元函数

1.重载为类成员函数,解释为

ObjectL.operator op(ObjectR)

     左操作数由ObjectL通过this指针传递,右操作数由参数ObjectR传递

2.重载为友元函数,解释为:

operator op(ObjectL,ObjectR)

   左右操作数都由参数传递

3.为什么要有操作符重载

   a=a+b;//int是基础类型,c++编译器已经为这些类型提供+操作

Complex c1=c1+c2;//Complex是自定义类型,编译器根本不知道如何加,但c++编译器会给你提供一个机制,让你实现自定义类型+

例子代码如下,重要的地方有标记:

class Complex{


friend Complex operator+(Complex &c1, Complex &c2);
friend Complex& operator++( Complex &c2);//前置++友元函数的实现
public:
Complex(int a = 0, int b = 0)
{
this->a = a;
this->b = b;
}
void print()
{
cout << a << "+" << b << "i" << endl;
}
private:
int a;
int b;
//通过类的成员函数实现-操作;左操作数被隐藏在this指针,右操作数就在参数中
public:
Complex operator-(Complex &c2)
{
Complex tmp;
tmp.a = this->a - c2.a;
tmp.b = this->b - c2.b;
return tmp;
}
public:
Complex& operator--()//通过类的成员函数实现--操作;左操作数被隐藏在this指针,右操作数就在参数中
{
this->a--;
this->b--;
return *this;
}
};
Complex operator+(Complex &c1, Complex &c2)//全局函数实现+操作写法
{
Complex tmp;
tmp.a = c1.a + c2.a;
tmp.b = c1.b + c2.b;
return tmp;
}
Complex& operator++( Complex &c2)//全局函数实现++操作写法
{
c2.a++;
c2.b++;
return c2;
}
void main()
{
Complex c1(1, 2), c2(3, 4);
Complex c3;
c3.print();
Complex c4 = operator+(c1,c2);//友元函数的写法
c4.print();
Complex c7= c1+c2;//友元函数的写法
c7.print();
Complex c5 =c1.operator-(c2);//累的成员函数写法
c5.print();
Complex c6 = c1-c2;
c6.print();
++c2;
c2.print();
--c2;
c2.print();


system("pause");
}

//后置--

Complex operator--(int)

{

Complex tmp = *this;

this->a --;

this->b --;

return tmp;

}

 

//后置++

Complex operator++(int)

{

Complex tmp = *this;

this->a ++;

this->b ++;

return tmp;

}

二.操作符重载的三个步骤(类成员函数方法进行的时候)

//目标:通过类的成员函数,完成操作符重载

1.要承认操作符重载是一个函数,完成操作符重载

2.写出函数调用语言 c1.operator-(c2)

3.完善函数原型

全局函数重载操作符友元用武之地

原因:

cout<<c1<<"链式编程测试"<<endl;

 operator<<(cout,c1);

 cout.operator<<(c1);