我的财产类别:
unit SubImage;
interface
type
TSubImage = class
private
{ private declarations }
function getHeight: Integer;
function getWidth: Integer;
procedure setHeight(const Value: Integer);
procedure setWidth(const Value: Integer);
protected
{ protected declarations }
public
{ public declarations }
property width : Integer read getWidth write setWidth;
property height : Integer read getHeight write setHeight;
published
{ published declarations }
end;
implementation
{ TSubImage }
function TSubImage.getHeight: Integer;
begin
Result:= height;
end;
function TSubImage.getWidth: Integer;
begin
Result:= width;
end;
procedure TSubImage.setHeight(const Value: Integer);
begin
height:= Value;
end;
procedure TSubImage.setWidth(const Value: Integer);
begin
width:= Value;
end;
end.
任务:
objSubImg.width:= imgOverview.width;
objSubImg.height:= imgOverview.heigh
有趣的错误:
stackoverflow at xxxxxx
我正在学习Delphi中的属性。我创建了一个类,但它给出了一个错误。我不明白,我的错误在哪里?
我也不明白为什么我们使用属性而不是setter / getter方法。无论如何有人可以帮助我,我该如何解决此代码?
我无法设置属性值。
这是一个非终止的递归。吸气剂看起来像这样:
function TSubImage.getHeight: Integer;
begin
Result := height;
end;
但是height
是财产。因此,编译器将其重写为:
function TSubImage.getHeight: Integer;
begin
Result := getHeight;
end;
这是一个非终止的递归。因此,堆栈溢出。
您需要声明字段来存储值:
type
TSubImage = class
private
FHeight: Integer;
FWidth: Integer;
function getHeight: Integer;
function getWidth: Integer;
procedure setHeight(const Value: Integer);
procedure setWidth(const Value: Integer);
public
property width: Integer read getWidth write setWidth;
property height: Integer read getHeight write setHeight;
end;
然后获取并设置值:
function TSubImage.getHeight: Integer;
begin
Result:= FHeight;
end;
procedure TSubImage.setHeight(const Value: Integer);
begin
FHeight:= Value;
end;
同样对于其他财产。
在这个简单的示例中,您不需要使用getter和setter函数。您可以这样声明属性:
property width: Integer read FWidth write FWidth;
property height: Integer read FHeight write FHeight;
但是我想您知道这一点,并且正在探索getter / setter函数的工作方式。
至于为什么我们使用属性而不是getter和setter函数,这归结为代码的清晰性和可读性。您可以用getter和setter函数替换属性。毕竟,这就是编译器要做的全部工作。但是写起来通常更清晰:
h := obj.Height;
obj.Height := h*2;
比
h := obj.GetHeight;
obj.SetHeight(h*2);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句