我猜测,C++的int类,应该是在类内定义了int数据类型。
——可能听起来有点绕,也就是我们平时在C++中使用的int是类而不是类型,该类底层是封装了int类型实现的。
我猜测它的实现👇
class my_int {
my_int(int init_a) {
a = init_a;
}
~my_int(){}
private:
int a;
};
直接给出实现👇
// ++a;
my_int& operator++() {
this->a = this->a + 1;
return *this;
}
// a++;
my_int operator++(int) {
int temp = this->a;
this->a = this->a + 1;
return temp;
}
返回值类型不同:++a应该返回引用,而a++返回的是新的对象,因此++a函数的返回值为int&,而a++的类型应为const int。
函数标识唯一——这里我的意思是,C++中是通过**{函数名 + 参数列表}来唯一标识一个函数的**,如果我们两个++都定义成👇
my_int operator++(){...}
my_int& operator++() {...}
可以发现,两个函数名相同,并且参数列表相同,那么C++中无法确定使用的是哪个函数,因此解决办法就是,在其中一个函数中添加int参数即可——又因为++a更像是一个原子操作,因此使用的是没有int的参数列表。
int类的简单实现为👇class my_int {
my_int(int init_a) {
a = init_a;
}
~my_int(){}
// a++;
my_int operator++(int) {
my_int temp = *this;
this->a = this->a + 1;
return temp;
}
// ++a;
my_int& operator++() {
this->a = this->a + 1;
return *this;
}
private:
int a;
};