Ada重载整数加法运算符运行报无限递归STORAGE_ERROR错误如何解决
问题原因
- 你在当前Test过程的作用域内重载了Integer类型的
+运算符,该重载会覆盖当前作用域下原生的Integer加法运算符 - 重载
+的实现代码中Left + Right实际调用的是你自定义的这个重载函数,而非系统原生加法,因此会触发无限递归,最终栈溢出抛出STORAGE_ERROR异常
解决方法
要在重载函数内部调用原生Integer加法,显式指定调用Standard标准包中定义的原生+运算符即可,Ada中可以通过运算符的函数名形式显式调用。
修正后完整代码
with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; procedure Test is function "+" (Left, Right : in Integer) return Integer is begin -- 显式调用Standard包的原生加法,避免递归 return -(Standard."+"(Left, Right)); end "+"; Left, Right : Integer; Result : Integer; begin Put("Type in two integers: "); Get(Left); Get(Right); -- 直接调用重载的+即可得到反相和 Result := Left + Right; Put("The "); if Result >= 0 then Put("negative "); else Put("positive "); end if; Put("sum of the two integers is: "); Put(Result); end Test;
效果验证
输入7 -10会输出反相和3,输入-10 7会输出反相和-3,完全符合需求,重载的运算符函数内部没有任何输入输出操作,也满足约束条件。
内容的提问来源于stack exchange,提问作者leun
相关产品推荐
相关产品推荐

