C++逆向分析——运算符重载

运算符重载

现在有一个类,其中有一个函数用于比较2个类的成员大小:

#include <stdio.h>
 
class Number {
private:
int x;
int y;
public:
Number(int x, int y) {
this->x = x;
this->y = y;
}
int Max(Number& n) {
return this->x > n.x && this->y > n.y;
}
};
 
void main() {
Number a(3,4),b(1,2);
int res = a.Max(b);
printf("%d \n", res);
return;
}

images/download/attachments/12714553/image2021-4-16_0-29-19.png

但是在这里,我们只是比较一下大小,确实用int类型,这有点浪费了,在C++中有一个类型叫bool类型,其返回就是真(1)、假(0),所以我们可以使用这个数据类型。

images/download/attachments/12714553/image2021-4-16_0-32-33.png

bool类型仅占用一个字节:

images/download/attachments/12714553/image2021-4-16_0-33-28.png

这样比较大小,多少还是有点麻烦,如果我们想实现跟其他的数一样直接比较大小该怎么办?直接使用a > b明显是不行的,因为编译器根本不知道你在比较什么。

这时候我们就需要使用运算符重栽,使用关键词:operator,例如我们想重载大于符号:

#include <stdio.h>

class Number {
private:
	int x;
	int y;
public:
	Number(int x, int y) {
		this->x = x;
		this->y = y;
	}
	bool operator>(Number& n) {
		return this->x > n.x && this->y > n.y;
	}
};

void main() {
	Number a(3, 4), b(1, 2);
	int res = a > b;
	printf("%d \n", res);
	return;
}

 

只需要在自定义类里面按照格式重载运算符即可:

images/download/attachments/12714553/image2021-4-16_0-39-16.png

 

我们看下vs2022下的汇编码:

 

 

 

也就是说运算符重载,其本质意义就是给重新定义运算符,或者说取一个别名;其在底层上和我们之前的代码是没有任何区别的,其价值就是为了便于写代码

重载其他的运算符:

Number operator++();
Number operator--();
Number operator+(Number& n);
Number operator-(Number& n);
Number operator*(Number& n);
Number operator/(Number& n);
bool operator<(Number& n);
bool operator==(Number& n);
bool operator>(Number& n) {
return this->x > n.x && this->y > n.y;
}

 

posted @ 2023-04-09 10:50  bonelee  阅读(29)  评论(0编辑  收藏  举报