YOK 发表于 2020-3-30 14:50:18

一个delphi函数重载的问题,麻烦路过的大牛指点一下~谢谢~

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;

type
TForm1 = class(TForm)
    edt1: TEdit;
    edt2: TEdit;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
private
    { Private declarations }
public
    { Public declarations }
end;

var
Form1: TForm1;

type
Tinfo = class(TObject)
public
    function showInfo(var str: string): string; overload; virtual;
    {重载 ,避免同名报错 reintroduce 进行隐匿Tinfo的同名函数}
    function showInfo(var num: integer): string; reintroduce; overload;
end;

implementation

var
info: Tinfo;
{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
info := Tinfo.Create; //实例化
edt1.Text := info.showInfo('这是字符串');
edt2.Text := info.showInfo(7);
info.Free;
end;

function Tinfo.showInfo(var str: string): string;
begin
Result := str;
end;

function Tinfo.showInfo(var num: integer): string;
begin
Result := IntToStr(num);
end;

end.


//报错
Unit1.pas(41): E2250 There is no overloaded version of 'showInfo' that can be called with these arguments
Unit1.pas(42): E2250 There is no overloaded version of 'showInfo' that can be called with these arguments
Project1.dpr(5): F2063 Could not compile used unit 'Unit1.pas'

但是我明明就在函数声明的时候加了overload,为啥还是报错~~~~???

ba21 发表于 2020-3-30 19:35:03

方法一:
    function showInfo(str: string): string; overload; virtual;
    {重载 ,避免同名报错 reintroduce 进行隐匿Tinfo的同名函数}
    function showInfo(num: integer): string; reintroduce; overload;

edt1.Text := info.showInfo('这是字符串');
edt2.Text := info.showInfo(7);

方法二:
形参 var str 表示传的是地址,在函数里面可以直接修改 button代码块中的 str,函数中又result:= str,
太多人余了不是????
形参加var 实参必须就是个变量名,是个变量

    function showInfo(var str: string): string; overload; virtual;
    {重载 ,避免同名报错 reintroduce 进行隐匿Tinfo的同名函数}
    function showInfo(var num: integer): string; reintroduce; overload;

procedure TForm1.btn1Click(Sender: TObject);
var
s:string;
i:Integer;
begin
s:='这是字符串';
i:=7;
info := Tinfo.Create; //实例化
edt1.Text := info.showInfo(s);
edt2.Text := info.showInfo(i);
info.Free;
end;

YOK 发表于 2020-3-31 09:28:53

ba21 发表于 2020-3-30 19:35
方法一:
    function showInfo(str: string): string; overload; virtual;
    {重载 ,避免同名报错 re ...

谢谢你的指导
因为形参加了var可以直接传地址进行修改
所以我刚开始就是考虑到代码冗余这块 就没有 进一步 声明function(就没有给返回值)
function Tinfo.showInfo(var str: string): string;
begin
Result := str;
end;

function Tinfo.showInfo(var num: integer): string;
begin
Result := IntToStr(num);
end;
但是不加这个就要报错 我不知道是我知识欠缺的原因,还是delphi软件版本的原因还是其他原因
在此基础上参考你的方法二 在按钮过程里加了两个形参并赋值 就实现了 方法的重载
再次万分感谢你的指导{:10_279:}
页: [1]
查看完整版本: 一个delphi函数重载的问题,麻烦路过的大牛指点一下~谢谢~