在 C++ 中重新定义基本类型 [英] Redefine basic types in C++

查看:49
本文介绍了在 C++ 中重新定义基本类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to redefine what an int is in C++?

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

The reason is because I want to simulate some Arduino code on a computer, without changing the Arduino code. For example to demonstrate overflow the same way, int would need to be 16-bits instead of the 32-bits it is on my machine.

所以基本上我想:

typedef int16_t int;

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

As well as doing the same for other data types that Arduino uses.

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

However I don't think that is possible, as it throws the error (unsurprisingly):

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

有什么方法可以轻松做到这一点吗?

Is there a way I can do this easily?

推荐答案

你不能重新定义int,但你可以停止根据int编写代码 并使用类型别名,如:

You can't redefine int but you can stop writing code in terms of int and use a type alias like:

typedef int int_type;

int main()
{
    int_type i = 0;

    // etc...
} 

然后你可以随意切换类型:

Then you can switch type when you want:

typedef int16_t int_type; // now using 16 bit integers

这篇关于在 C++ 中重新定义基本类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆