在C++中重新定义基本类型

Redefine basic types in C++

本文关键字:定义 类型 C++ 新定义      更新时间:2023-10-16

是否可以重新定义C++中的int

原因是因为我想在计算机上模拟一些Arduino代码,而不更改Arduino代码。例如,要以相同的方式演示溢出,int需要是 16 位而不是我机器上的 32 位。

所以本质上我想:

typedef int16_t int;

以及对Arduino使用的其他数据类型执行相同的操作。

但是我认为这是不可能的,因为它会引发错误(不出所料(:

error: cannot combine with previous 'type-name' declaration specifier

有没有办法让我轻松做到这一点?

您无法重新定义int您可以停止根据int编写代码并使用类型别名,如下所示:

typedef int int_type;
int main()
{
    int_type i = 0;
    // etc...
} 

然后,您可以根据需要切换类型:

typedef int16_t int_type; // now using 16 bit integers