如何在不创建递归函数的情况下重载Ada中的'='运算符? [英] How can I overload the '=' operator in Ada without creating a recursive function?
问题描述
FUNCTION "=" (lString1, lString2 : IN lString) RETURN boolean IS
IF lString1 = NULL AND lString2 = NULL THEN
RETURN true;
ELSIF lString1 = NULL OR lString2 = NULL THEN
RETURN false;
END IF;
我正在尝试重载Ada中的相等运算符.每次我在函数中使用运算符'='时,都会导致递归导致栈溢出,而不是使用我需要的ada定义运算符.有什么办法可以将它与我的重载运算符区分开来吗?
I'm trying to overload the equality operator in Ada. Each time I use the operator '=' within the function it causes a recursion which leads to a stack overflow, rather than use the ada defined operator which I need. Is there a way to differentiate it from my overloaded operator?
推荐答案
通过引入非重载的实用函数来进行访问类型比较,OP的函数定义以及所需的语法修复,并进行修改以使用该实用函数,可以工作.
By introducing a non-overloaded utility function to do the access type comparisons, the OP's function definition, with the needed syntax fixes and modified to use the utility function, can be made to work.
尽管如此,我还是很困惑为什么编译器(GNAT)拒绝使用"=作为Standard." =来指定不兼容的参数".
I'm still puzzled, though, as to why invoking "=" as Standard."=" is rejected by the compiler (GNAT) for specifying "incompatible arguments".
with Text_IO; use Text_IO;
procedure non_recursive_equals is
type Lstring is access String;
-- Be aware, the ordering of the functions here is important!
function Is_Equal(Lstring1, Lstring2 : in Lstring) return Boolean is
begin
return Lstring1 = Lstring2;
end Is_Equal;
function "=" (lString1, lString2 : in Lstring) return Boolean is
begin
if Is_Equal(LString1, null) and Is_Equal(LString2, null) then
return True;
elsif Is_Equal(LString1, null) or Is_Equal(LString2, null) then
return False;
end if;
return False;
end "=";
L1, L2 : Lstring := null;
begin
Put_Line("L1 and L2 null: " & Boolean'Image(L1 = L2));
L2 := new String(1..10);
Put_Line("L2 not null : " & Boolean'Image(L1 = L2));
end non_recursive_equals;
这是使用重命名子句的另一种方式:
Here's another way, using a renames clause:
with Text_IO; use Text_IO;
procedure non_recursive_equals is
type Lstring is access String;
function Is_Equal (lString1, lString2 : in Lstring) return Boolean is
begin
if lString1 = null and lString2 = null then
return True;
elsif lString1 = null or lString2 = null then
return False;
end if;
return False;
end Is_Equal;
function "=" (Lstring1, Lstring2 : in Lstring) return Boolean renames
Is_Equal;
L1, L2 : Lstring := null;
begin
Put_Line ("L1 and L2 null: " & Boolean'Image (L1 = L2));
L2 := new String (1 .. 10);
Put_Line ("L2 not null : " & Boolean'Image (L1 = L2));
end non_recursive_equals;
这篇关于如何在不创建递归函数的情况下重载Ada中的'='运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!