运算符重载
对于类所生成的对象有大量重复的操作,可以将这些函数使用运算符重载来完成,使得运算符能够对类的对象进行作用。
#include<iostream>
#include<stdio.h>
class Rect
{
public:
int width;
int height;
Rect(int _w, int _h)
{
width = _w;
height = _h;
}
//通过运算符重载
friend Rect operator + (Rect &R1, Rect &R2)
{
Rect rect(0, 0);
rect.height = R1.height + R2.height;
rect.width = R1.width + R2.width;
return rect;
}
Rect operator ++()
{
this->width += 1;
this->height += 1;
return (*this);
}
//通过成员函数
void add(Rect &R1)
{
this->height = this->height + R1.height;
this->width = this->width + R1.width;
}
};
int main()
{
Rect R1(10, 10);
Rect R2(5, 5);
//通过运算符重载
R1 = R1 + R2;
printf("R1--->width %d, R1--->height %d\n", R1.width, R1.height);
//通过成员方法
R1.add(R2);
printf("R1--->width %d, R1--->height %d\n", R1.width, R1.height);
//通过运算符重载
++R1;
printf("R1--->width %d, R1--->height %d\n", R1.width, R1.height);
getchar();
return 0;
}
仿函数
对类中()
的进行重载,使得由类创建的对象,具有类似函数调用的功能。这种运算符重载称之为仿函数,仿函数其实质也就是一个函数。
#include<iostream>
#include<stdio.h>
class Rect
{
public:
int width;
int height;
Rect(int _w, int _h)
{
width = _w;
height = _h;
}
//通过运算符重载
friend Rect operator + (Rect &R1, Rect &R2)
{
Rect rect(0, 0);
rect.height = R1.height + R2.height;
rect.width = R1.width + R2.width;
return rect;
}
Rect operator ++()
{
this->width += 1;
this->height += 1;
return (*this);
}
void operator ()(int x)
{
printf("width is %d, width add x is %d \n", this->width, this->width + x);
}
//通过成员函数
void add(Rect &R1)
{
this->height = this->height + R1.height;
this->width = this->width + R1.width;
}
};
int main()
{
Rect R1(10, 10);
Rect R2(5, 5);
R1 = R1 + R2;
printf("R1--->width %d, R1--->height %d\n", R1.width, R1.height);
R1.add(R2);
printf("R1--->width %d, R1--->height %d\n", R1.width, R1.height);
++R1;
printf("R1--->width %d, R1--->height %d\n", R1.width, R1.height);
R1(5);
getchar();
return 0;
}