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

Delphi如何创建并分配整数栈?创建遇报错求助

解决Delphi中整数栈的创建问题

别着急,我来帮你捋清楚在Delphi里创建整数栈的正确步骤——你遇到的报错大概率是因为没引入正确的单元,或是对Delphi栈类的用法没摸透。

第一步:先引入正确的单元

Delphi里的栈类分两种,对应不同的单元:

  • 如果用类型安全的泛型栈(最推荐存整数的方案),必须引入 System.Generics.Collections 单元;
  • 旧的 TObjectStack 属于 Contnrs 单元,但它只能存对象,没法直接存整数,得把整数包装成对象(比如自定义TInteger类),非常麻烦,完全不适合你的需求。

第二步:在过程里正确声明和创建栈

你之前直接写genericstack:TStack;报错,是因为TStack是泛型类,必须明确指定要存的类型(比如<Integer>),而且得手动创建实例。给你一个完整的可运行示例:

procedure TestIntegerStack;
var
  IntStack: TStack<Integer>; // 声明泛型整数栈,指定类型为Integer
  CurrentNum: Integer;
begin
  IntStack := TStack<Integer>.Create; // 创建栈的实例
  try
    // 入栈操作:把整数压入栈
    IntStack.Push(10);
    IntStack.Push(20);
    IntStack.Push(30);

    // 出栈操作:从栈顶依次取出整数
    while IntStack.Count > 0 do
    begin
      CurrentNum := IntStack.Pop;
      ShowMessage(IntToStr(CurrentNum)); // 会按30、20、10的顺序弹出
    end;
  finally
    IntStack.Free; // 务必释放栈实例,避免内存泄漏
  end;
end;

为什么你之前的声明会报错?

  • genericstack:TObjectStack;:这个类是为存储对象设计的,不能直接存Integer这种值类型,强行用只会徒增麻烦;
  • genericstack:TStack;:TStack是泛型类,必须附带类型参数(比如<Integer>),编译器需要明确知道你要存什么类型的数据,否则就会报错。

补充:如果你用的是旧版Delphi(2009之前)

泛型是Delphi 2009才引入的,要是你用的版本更早,可以自己手动实现一个简单的整数栈,用动态数组模拟就行:

// 先自定义一个整数栈类
type
  TIntegerStack = class
  private
    FStackItems: array of Integer;
  public
    procedure Push(const Value: Integer);
    function Pop: Integer;
    function Peek: Integer; // 查看栈顶元素但不弹出
    property Count: Integer read Length(FStackItems);
  end;

procedure TIntegerStack.Push(const Value: Integer);
begin
  SetLength(FStackItems, Length(FStackItems) + 1);
  FStackItems[High(FStackItems)] := Value;
end;

function TIntegerStack.Pop: Integer;
begin
  if Count = 0 then
    raise Exception.Create('栈为空,无法执行弹出操作');
  Result := FStackItems[High(FStackItems)];
  SetLength(FStackItems, Length(FStackItems) - 1);
end;

function TIntegerStack.Peek: Integer;
begin
  if Count = 0 then
    raise Exception.Create('栈为空,无法查看栈顶元素');
  Result := FStackItems[High(FStackItems)];
end;

然后在过程里使用这个自定义类:

procedure TestCustomStack;
var
  IntStack: TIntegerStack;
begin
  IntStack := TIntegerStack.Create;
  try
    IntStack.Push(5);
    IntStack.Push(15);
    ShowMessage(IntToStr(IntStack.Pop)); // 会显示15
  finally
    IntStack.Free;
  end;
end;

按照这个步骤来,应该就能顺利创建并使用整数栈了~

内容的提问来源于stack exchange,提问作者Rosie Murphy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:02:51