有没有可能将未声明的常量作为某个函数的无类型参数传递给nil?
我有一些类似这样的函数,并且我想通过将一些常量传递给参数来满足编译器的要求。在内部,我根据参数进行决策。我知道我可以使用指针来代替无类型参数,但对于我的情况来说,这更加方便。
现在我得到了“E2250没有重载版本的'RS232_SendCommand'可以用这些参数调用”的错误提示。
这段代码是可行的,但如果我不需要声明变量会更好。
解决方案是使用类似以下内容的东西。
function RS232_SendCommand(const Command: Integer): Boolean; overload;
begin
// is it possible to pass here an undeclared constant like nil in this example?
Result := RS232_SendCommand(Command, nil, 0);
end;
function RS232_SendCommand(const Command: Integer; const Data; const Size: Integer): Boolean; overload;
begin
...
end;
这段代码是可行的,但如果我不需要声明变量会更好。
function RS232_SendCommand(const Command: Integer): Boolean; overload;
var
Nothing: Pointer;
begin
Result := RS232_SendCommand(Command, Nothing, 0);
end;
解决方案是使用类似以下内容的东西。
function RS232_SendCommand(const Command: Integer): Boolean; overload;
begin
// as the best way looks for me from the accepted answer to use this
Result := RS232_SendCommand(Command, nil^, 0);
// or it also possible to pass an empty string constant to the untyped parameter
// without declaring any variable
Result := RS232_SendCommand(Command, '', 0);
end;
我这样做是因为我有些命令在发送后还会附带数据。
感谢帮助。
nil^
可以被归类为优雅的代码!;-) 你只需记住,这不会对 nil 指针进行反引用。 - David Heffernan