这是布赖恩·德拉蒙德在上述评论中所写内容的扩展。当我在 Ada 编程语言中进行 OOP 并希望表达具有一些私有和公共属性的“类”的想法时,我会写(使用马特的例子):
type Car_Type is tagged private;
function I_Am_A_Public_Attribute (This : Car_Type) return Integer;
function I_Am_Another_Public_Attribute (This : Car_Type) return Integer;
private
type Car_Type is tagged
record
I_Am_A_Public_Attribute : Integer;
I_Am_Another_Public_Attribute : Integer;
I_Am_A_Private_Attribute : Integer;
I_Am_Another_Private_Attribute : Integer;
end record;
function I_Am_A_Public_Attribute (This : Car_Type) return Integer is (This.I_Am_A_Public_Attribute);
function I_Am_Another_Public_Attribute (This : Car_Type) return Integer is (This.I_Am_Another_Public_Attribute);
这个想法是为每个想要公开的属性设置一个获取函数。实际上,上面的代码并不是我所说的“Ada 风格”。为了利用 Ada 的优势,为每个属性定义一个新类型:
type I_Am_A_Public_Attribute_Type is new Integer;
type I_Am_Another_Public_Attribute_Type is new Integer;
type Car_Type is tagged private;
function I_Am_A_Public_Attribute (This : Car_Type) return I_Am_A_Public_Attribute_Type;
function I_Am_Another_Public_Attribute (This : Car_Type) return I_Am_Another_Public_Attribute_Type;
private
type I_Am_A_Private_Attribute_Type is new Integer;
type I_Am_Another_Private_Attribute_Type is new Integer;
type Car_Type is tagged
record
I_Am_A_Public_Attribute : I_Am_A_Public_Attribute_Type;
I_Am_Another_Public_Attribute : I_Am_Another_Public_Attribute_Type;
I_Am_A_Private_Attribute : I_Am_A_Private_Attribute_Type;
I_Am_Another_Private_Attribute : I_Am_Another_Private_Attribute_Type;
end record;
function I_Am_A_Public_Attribute (This : Car_Type) return I_Am_A_Public_Attribute_Type is (This.I_Am_A_Public_Attribute);
function I_Am_Another_Public_Attribute (This : Car_Type) return I_Am_Another_Public_Attribute_Type is (This.I_Am_Another_Public_Attribute);
请注意,如果将 get-function 与错误的属性混合在一起,则会出现编译时错误。这是“Ada,我们信任强类型”的一个很好的例子。
编辑:一旦我从性能的角度调查了公共属性和获取函数之间的选择是否有任何偏好。我发现使用 GNAT 编译器时性能没有差异。我没有用任何其他编译器尝试过同样的实验。