前置操作符与后置操作符
i++;//i作为返回值,i自增1
++i;
编译后丢失原生意义
++操作符重载
- 全局函数和成员函数均可进行重载
- 重载前置++不要额外参数
- 重载后置++需要额外的int占位参数
#include <iostream>
#include <string>
using namespace std;
class Test
{
int mValue = 0;
public:
Test(int i)
{
mValue = i;
}
int value()
{
return mValue;
}
Test& operator ++ ()//++t效率高
{
++mValue;
return *this;//返回当前对象
}
Test operator ++ (int)//Test& ??? t++效率低
{
Test ret(mValue);
mValue++;
return ret;//返回当前对象
}
};
int main()
{
Test t(0);
cout << t.value() << endl;
Test tt = ++t;
tt = t++;
cout << tt.value() << endl;
cout << t.value() << endl;
return 0;
}
对于基础类型的变量
- 前后置++效率基本相同
对于类类型
- 前置++效率高,尽量
复数类完善
#ifndef _COMPLEX_H_
#define _COMPLEX_H_
class Complex
{
double a;
double b;
public:
Complex(double a = 0, double b = 0);
double getA();
double getB();
double getModulus();
Complex operator + (const Complex& c);
Complex operator - (const Complex& c);
Complex operator * (const Complex& c);
Complex operator / (const Complex& c);
bool operator == (const Complex& c);
bool operator != (const Complex& c);
Complex& operator = (const Complex& c);
Complex& operator ++();
Complex operator ++(int);
};
#endif
#include "Complex.h"
#include "math.h"
Complex::Complex(double a, double b)
{
this->a = a;
this->b = b;
}
double Complex::getA()
{
return a;
}
double Complex::getB()
{
return b;
}
double Complex::getModulus()
{
return sqrt(a * a + b * b);
}
Complex Complex::operator + (const Complex& c)
{
double na = a + c.a;
double nb = b + c.b;
Complex ret(na, nb);
return ret;
}
Complex Complex::operator - (const Complex& c)
{
double na = a - c.a;
double nb = b - c.b;
Complex ret(na, nb);
return ret;
}
Complex Complex::operator * (const Complex& c)
{
double na = a * c.a - b * c.b;
double nb = a * c.b + b * c.a;
Complex ret(na, nb);
return ret;
}
Complex Complex::operator / (const Complex& c)
{
double cm = c.a * c.a + c.b * c.b;
double na = (a * c.a + b * c.b) / cm;
double nb = (b * c.a - a * c.b) / cm;
Complex ret(na, nb);
return ret;
}
bool Complex::operator == (const Complex& c)
{
return (a == c.a) && (b == c.b);
}
bool Complex::operator != (const Complex& c)
{
return !(*this == c);
}
Complex& Complex::operator = (const Complex& c)
{
if( this != &c )
{
a = c.a;
b = c.b;
}
return *this;
}
Complex& Complex::operator ++()
{
a = a + 1;
b = b + 1;
return *this;
}
Complex Complex::operator ++(int)
{
Complex ret(a, b);
a = a + 1;
b = b + 1;
return ret;
}
#include <iostream>
#include <string>
#include "Complex.h"
using namespace std;
int main()
{
Complex c(0, 0);
Complex b = c++;
cout << b.getA() << endl;
cout << b.getB() << endl;
return 0;
}
总结
- 对于基础类型的变量,- 前后置++效率基本相同
- 对于类类型, 前置++效率高,尽量