运算符没有重载:"常量字符串" +"无类型"

时间:2014-08-22 13:32:14

标签: delphi comparison operator-overloading pascal procedure

我正在从一个数据集读取一个SQL函数然后写入一个文件,我创建了一个小程序,它检查空字段然后用null替换它们,非空字段在它们周围放置引号

然而,当我转到编译时,我得到了错误

Error: Operator is not overloaded: "Constant String" + "untyped"

坦率地说我不知道​​这意味着什么,我检查了fpc解析器消息帮助,其中说

You’re trying to use an overloaded operator when it is not overloaded for this type.

我发现更令人困惑。有人可以帮帮我吗?我认为这是因为我在我的程序中进行了比较,但可能是错误的。

procedure isNull(str : AnsiString);
  begin
    if str = EmptyStr then
      str := Null
    else
      str := '' + str + '';
  end;

procedure TForm1.Button2Click(Sender: TObject);
var
  i : Integer;
  addLine, f : string;
  list : TStringList;
begin
  f := 'info.sql';
  list := TStringList.Create;

  with AddressData do begin
    for i := 0 to RecordCount do begin

    RecNo := i;
    addLine := 'CALL CONT__Add(' + isNull(Fields[0].AsString) +')'; // Much more of this but fails at first call of procedure
    list.Add(addLine);
    end;
  list.SaveToFile(f);
  list.free;
   end;
end;

3 个答案:

答案 0 :(得分:2)

addLine := 'CALL CONT__Add(' + isNull(Fields[0].AsString) +')';

这会失败,因为isNull是一个过程,因此不会评估任何内容。为了使这个代码编译isNull,需要将一个函数的返回类型强制转换为字符串。

我发现很难知道你应该如何改变你的计划,因为它不是很明显它想要做什么。尤其是因为名为isNull的函数应该针对null测试其输入并返回布尔值。

我还承认

的困惑
str := '' + str + '';

它什么都不做,不对str的值进行修改。

我最好的猜测是你想要这样的东西:

function PrepareField(const str: string): string;
begin
  if str = '' then
    Result := Null
  else
    Result := '''' + str + '''';
end;

这段代码让我担心SQL注入。你有这个风险吗?

答案 1 :(得分:0)

定义isNull如下编译。感谢指针大卫。

function isNull(str : AnsiString) : String;
begin
  if str = EmptyStr then
    str := Null
  else
    str := '' + str + '';
  isNull := str;
end; 

答案 2 :(得分:0)

您的代码中存在多个错误

procedure isNull(str : AnsiString); // str assignments inside procedure does not takes effect outside procedure, use var str
  begin
    if str = EmptyStr then
      str := Null // Incompatible types AnsiString (str) and Variant (Null). May be you means 'Null' (in quotes)?
    else
      str := '' + str + ''; // concatenation with empty strings, use QuotedStr(str)
  end;

正如@DavidHeffernan所说,isNull是一个程序,不能以函数方式使用。

相关问题