c++ operator逐级推演
通过友元函数或全局函数实现操作符重载
#include <iostream>
using namespace std;
class Complex
{
public:
int _a;
int _b;
public:
Complex(int a = 0,int b = 0)
{
_a = a;
_b = b;
}
void printCom()
{
cout << _a << "+"<< _b<<"i"<<endl;
}
};
Complex comAdd(Complex& c1,Complex& c2)
{
Complex temp;
temp._a = c1._a + c2._a;
temp._b = c1._b + c2._b;
return temp;
}
Complex operator+(Complex& c1,Complex& c2)
{
Complex temp;
temp._a = c1._a + c2._a;
temp._b = c1._b + c2._b;
return temp;
}
int main()
{
Complex c1(1,2), c2(3,4);
Complex c3 = comAdd(c1,c2);
c3.printCom();
Complex c4 = operator+(c1,c2);
c4.printCom();
return 0;
}
无形之中把加好设置成函数了,也就是操作符重载。操作符重载采用的是函数实现的机制。
类成员函数实现操作符重载
类型 类名::operator op(参数表)
{
}
op为可重载的运算符
Complex operator-(Complex& c)
{
Complex temp;
temp._a = _a - c._a;
temp._b = _b - c._b;
return temp;
}
[]运算符的重载
- Array类
#ifndef _ARRAY_H_
#define _ARRAY_H_
class Array
{
private:
int mLength;
int* mSpace;
public:
Array(int length);
Array(const Array& obj);
int length();
void setData(int index, int value);
int getData(int index);
~Array();
public:
int& operator[] (int i);
};
#endif
#include "iostream"
#include "Array.h"
using namespace std;
Array::Array(int length)
{
if( length < 0 )
{
length = 0;
}
mLength = length;
mSpace = new int[mLength];
}
Array::Array(const Array& obj)
{
mLength = obj.mLength;
mSpace = new int[mLength];
for(int i=0; i<mLength; i++)
{
mSpace[i] = obj.mSpace[i];
}
}
int Array::length()
{
return mLength;
}
void Array::setData(int index, int value)
{
mSpace[index] = value;
}
int Array::getData(int index)
{
return mSpace[index];
}
Array::~Array()
{
mLength = -1;
delete[] mSpace;
}
//printf("array %d: %d\n", i, a2[i]);
//a2[i] = 0
int& Array::operator[] (int i)
{
return mSpace[i];
}
int& Array::operator[] (int i) 这里必须是引用,因为[]的应用场景有两处。
- a[i] = i;//left value
- cout << a[i];
函数的返回值要当左值,必须使用引用作为函数类型。
=的重载及连等实现
Array& operator= (Array& a);//.h中声明
Array& Array::operator= (Array& a)//.cpp中实现
{
if(mSpace != NULL)
{
delete[] mSpace;
mLength = 0;
}
mLength = a.mLength;
mSpace = new int[mLength];
for (int i = 0; i < mLength; ++i)
{
mSpace[i] = a[i];
}
return *this;
}
这里如果不返回引用,返回Array,则最好要写上拷贝构造函数(类成员中有指针变量),还是引用简单方便。
前置++与后置++重载
//前置
Complex& operator++()
{
this->a ++;
this->b ++;
return *this;
}
//后置,先参与运算,再自增,所以使用临时变量缓存下来
//return temp会调用类的拷贝构造函数相当于延长生存期
Complex operator++(int)
{
Complex temp = *this;
this.a++;
this.b++;
return temp;
}