【发布时间】:2013-09-12 14:42:12
【问题描述】:
我有以下 C++ 代码:
标题:(在类内)
virtual const bigint &getPopulation() ;
实现:
static bigint negone = -1 ;
const bigint &hlifealgo::getPopulation() {
// note: if called during gc, then we cannot call calcPopulation
// since that will mess up the gc.
if (!popValid) {
if (inGC) {
needPop = 1 ;
return negone ;
} else {
calcPopulation(root) ;
popValid = 1 ;
needPop = 0 ;
}
}
return population ;
}
我将它移植到 Delphi,它工作得很好。 我仍然对 const 返回类型有点困惑。
我可以忽略翻译中的const,还是这里有什么要注意的?
这个概念在 Delphi 中有类似物吗?
【问题讨论】:
-
我假设 BigInt 通过引用传递(因为它是 32 位代码并且通过引用传递 64 位值更快)并且 const 防止它被更改。
-
类型是
const bigint&所以是的,它是一个参考 -
在这种情况下,等效项是:
procedure getP(var population: int64);,但var引用是const(如果有意义的话) -
这并不等同,约翰。在 C++ 中,调用者可以将结果存储在 const 引用变量中。对该函数返回的
population变量的任何进一步修改也可以在该other const-reference 变量中观察到。为了模仿这种行为,您需要function getP: PInt64并承诺调用者不会使用该指针来修改指向的数据。底线是 Delphi 没有将 const 作为 type 一部分的概念。 -
@RobKennedy,好的,我现在明白了,
&使函数返回一个指针(通过引用传递),因为它确实是一个指针,需要const以防止您丢失它。