C 中的 typedef 和 A​​da 中的应用程序定义类型之间的区别

Difference between typedef in C and application-defined types in Ada

所以我正在学习 Ada 中的应用程序定义类型,它看起来像 C 编程语言中的 typedef。但是,如果我使用 typedef 在 C 中为预定义类型创建了一个新名称,我仍然可以这样做:

typedef int my_int;
int a = 5;
my_int b = a; -- No problem

但是如果我在 Ada 上尝试这个:

type my_int is new Integer;
a : Integer := 5;
b : my_int  := a; -- Causes some error

所以我的问题是,我的理解是否正确,在 C 中 my_int 只是一个别名或类型的新名称 int 而不是新类型,而在 Ada 中 my_int是一种完全不同的数据类型本身,而不仅仅是类型 Integer.

的新名称

that is my understanding correct that in C my_int is just an alias or a new name of type int and not a new type whereas in Ada my_int is a completely different data type itself not just a new name for type Integer.

非常模糊,但它是否是新类型与它无关 - 在 C 中,您也可以毫无问题地执行 char c = 1.123L;。不同之处在于,C 语言在此上下文中具有 implicit 转换——而 Ada 则没有。总的来说,这些是不同的语言。

首先,在 Ada 中声明类型与在 C 中声明类型 typedef 不同。typedef 更像是创建现有简单类型的别名。在 Ada 中执行此操作的正确方法是将类型声明为 subtype。在您的示例中,它应该是(正如 Zerte 在评论中建议的那样):

subtype my_int is Integer;

在那种情况下,您的代码将起作用。旁注:在 Ada 中创建记录与在 C 中使用 typedef.

创建结构非常相似

Ada 是一种非常 强类型的语言。如果不进行类型转换(在 C 系列语言中称为“强制转换”),则无法将一种类型分配给另一种类型。例如:

type My_Int is new Integer;
type My_Int2 is new Integer;

这两种类型彼此不兼容或与其父类型 Integer 不兼容,如果要混合使用它们,则必须使用类型转换。

作为一个从 C 到 Ada 的人,我认为,如果你想了解 Ada,最重要的是了解 Ada 类型系统。和C完全不同,Ada更注重数据表示,C更注重操作数据。