You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 23:36:03