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,例如我们想重载大于符号:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#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 @   bonelee  阅读(39)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
历史上的今天:
2020-04-09 OWASP TOP10 Web应用十大安全风险_2017
2020-04-09 移动互联网恶意程序描述格式 ——移动端恶意软件分类再合适不过了
2020-04-09 用短信传播病毒:最新Android手机勒索软件Koler
2020-04-09 2019年Android恶意软件专题报告:未来移动安全呈现四大趋势——资费消耗与隐私窃取分别以高达46.8%和41.9%的占比,成为横行无忌的主要恶意软件类型,其次分别为远程控制、流氓行为、恶意扣费和欺诈软件。
2020-04-09 2018年Android恶意软件专题报告
2020-04-09 浅析Android恶意应用及其检测技术
2020-04-09 Android恶意软件特征及分类
点击右上角即可分享
微信分享提示