c++运算符重载
1、为什么要对运算符进行重载?
c++中的运算符操作对象只局限于基本的内置数据类型,但是对于自定义的类型(类)是没有办法操作的。比如如下操作:p1 + p2 ,如果不重载将不能实现: p1 + p2
class{
private:
int x;
int y;
public:
...
}
int main(int argc, char **argv)
{
Point p1(1, 2);
Point p2(2, 3);
Point sum = p1 + p2;
}
2、c++运算符重载的本质
运算符实质上是一个函数,既然是函数当然可以重载。要重载运算符,需要使用如下格式:
<返回类型说明符> operator <运算符符号>(<参数表>)
{
<函数体>
}
3、实例
3.1、+号重载
class Point{
private:
int x;
int y;
public:
...
friend Point operator+(Point &p1, Point &p2);
};
Point add(Point &p1, Point &p2)
{
Point n;
n.x = p1.x + p2.y
n.y = p1.y + p2.y;
return n;
}
Point operator+(Point &p1, Point &p2)
{
cout<<"Point operator+(Point &p1, Point &p2)"<<endl;
Point n;
n.x = p1.x + p2.x;
n.y = p1.y + p2.y;
return n;
}
int main(int argc, char **argv)
{
Point p1(1, 2);
Point p2(2, 3);
Point sum = p1 + p2;/* 直接调用: operator+(p1, p2)也是可以的 */
return 0;
}
3.2、前++和后++的重载
class Point{
private:
int x;
int y;
public:
...
void printInfo()
{
cout<<"("<<x<<", "<<y<<")"<<endl;
}
friend Point operator++(Point &p);
friend Point operator++(Point &p, int a);
};
Point operator++(Point &p) /* 前++ */
{
cout<<"++p"<<endl;
p.x += 1;
p.y += 1;
return p;
}
Point operator++(Point &p, int a) /* 后++ */
{
cout<<"p++"<<endl;
Point n;
n = p;
p.x += 1;
p.y += 1;
return n;
}
int main(int argc, char **argv)
{
Point p1(1, 2);
Point p2(2, 3);
Point n = ++p1;
n.printInfo();
p1.printInfo();
cout << "******************"<<endl;
Point m = p2++;
m.printInfo();
p2.printInfo();
return 0;
}
在重载前++时返回一个对象的引用也是可以的,如下:
Point &operator++(Point &p)
{
cout<<"++p"<<endl;
p.x += 1;
p.y += 1;
return p;
}
4、返回一个对象和返回一个对象的引用在效率上有什么区别?
在函数中返回一个对象,会先创建一个临时对象,根据返回值类型构造临时对象,会调用构造函数,在对象使用完后会调用析构函数,消耗较多的执行时间。在返回一个对象的引用是则不会出现此问题。
5、什么时候返回一个对象,什么时候返回一个对象的引用?
在不影响结果的前提下返回引用,提高程序的执行效率。比如:前++返回引用正确,后++返回引用会影响结果,错误。