c++ - 从 C++ 到 ObjectPascal 的翻译检查哪个更好

标签 c++ pointers translate delphi

我正在将一些 C++ 代码转换为 ObjectPascal(第一次),C++ 对我来说还是相当陌生。

C++ 头文件如下所示:

class RenumFd {
public:
    RenumFd(int length);
    ~RenumFd();
    void CompFd(double *buff);

//...other public functions cut for space

private:
    void rmfd(int n, int isgn, double *a, int *ap, double *kw);

//...other private functions cut for space

    int _length;
    int *_ap;
    double *_kw;
}

我是这样翻译的:

Type
 TRenumFD = class
 private
   _length: integer;
   _ap: Pinteger;
   _kw: Pdouble;
   procedure rmfd(n:integer; isgn:integer; var a:double; var ap:integer; var kw:double);

//... other procedures cut for space   

public
  constructor Create(const length:integer);
  destructor  Destroy(); override;
  procedure CompFd(var buff:double);
end;

我读到在 C++ 中用作参数的指针应该在 Object Pascal 中设置为 var 参数。是这样吗,还是我应该坚持更直译(担心以后被咬)。

在 C++ 构造函数中还有以下代码,我不确定是否在一行中。

RenumFd::RenumFd(int length) {
    _length = length;
    _ap = new int[2 + (1 << ((int)(log(2.0 + length) + 0.5) / 2))];
    _ap[0] = 0;  <-- is this setting the pointer to nil, or assigning 0?

    //...

}

我不确定我是否应该将 Object Pascal 中的那行翻译为用零填充第一个元素或分配给 nil:

_ap := AllocMem(2 + (1 shl (trunc(ln(2.0 + length) + 0.5) / 2))) * sizeOf(integer));
_ap := nil;

也许我过于努力地猜测其意图?

最佳答案

使用 var 还是指针实际上取决于它的使用方式,以及它是否可以设置为 nil。通常 var 更好,但指针有其用途。您没有提供足够的代码来显示哪个决定是最好的。

至于数组分配,动态数组会是比AllocMem()更好的选择:

type
  RenumFd = class
  public
    constructor Create(length: Integer);
    //...    
  private
    _ap: array of Integer;
    //...
  end;

constructor RenumFd.Create(length: Integer);
begin
  SetLength(_ap, 2 + (1 shl (Trunc(log(2.0) + 0.5) div 2)));
  _ap[0] := 0; // <-- assigns 0 to the first integer in the array
  //...
end;

关于c++ - 从 C++ 到 ObjectPascal 的翻译检查哪个更好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21487952/

相关文章:

c++ - C/C++指针问题

c++ - 搜索 vector 成员的前n%个C++

c++ - OpenCV "Undefined reference to ' cv::imread' 等 C++

c++ - 正整数 N 作为使用堆栈的正整数之和

c++ - 是否有用于使用智能指针检测 "Memory Leaks"的 Valgrind

CSS - "initial"是或曾经是转换转换(X、Y 或 Z)函数的有效参数?

java - 绘画应用程序 : Drag free-form lines (paths) with AffineTransform

python - PyPy 翻译 64 位

c++ - 在 C++ 中创建一个包含不同类型事件的最小优先级队列

c++ - 重载 < 运算符的正确方法?