导致访问违规的无法访问的值

时间:2015-10-14 09:51:50

标签: delphi delphi-7

我有一个自行车程序(TObject)

在调用我的Create方法时,我收到访问冲突错误00453359和地址00000004

constructor MyBike.Create(iPrice, iStroke, iYear, iCC: Integer; sName,
  sModel: string);
begin
  fCC := iCC; // <- Here is the error
  fPrice := iPrice;
  fStroke := iStroke;
  fYear := iYear;
  fName := sName;
  fModel := sModel; 

当我观察该行时,它表示它是inaccessible value,就像那里的所有变量一样。

以下是我班上的其他人:

type
  MyBike = class(TObject)
  private
    fCC, fStroke, fYear, fPrice: Integer; //I will at a later stage use fPrice as a currency
    fName, fModel: string;
  public
    constructor Create(iPrice, iStroke, iYear, iCC: Integer; sName, sModel:
      string);
    function GetValues: string;
  end;

implementation

{ MyBike }

constructor MyBike.Create(iPrice, iStroke, iYear, iCC: Integer; sName,
  sModel: string);
begin
  fCC := iCC;
  fPrice := iPrice;
  fStroke := iStroke;
  fYear := iYear;
  fName := sName;
  fModel := sModel;
end;

和我的主要单位:

private
    { Private declarations }
    NewBike : MyBike;
  public
    { Public declarations }       
  end;

var
  Form1: TForm1;
  redtSavedObject: TRichEdit;
  btnClearSavedObject: TButton;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
begin
  btnSaveToText.Enabled := False;
  btnSavetodata.Enabled := False;
end;

procedure TForm1.btnSaveasObjectClick(Sender: TObject);
var
  Price, Year, CC, Stroke : Integer;
  Name, Model : String;

begin
  Price := StrToInt(edtPrice.Text); //All of these values are fine
  Year := StrToInt(edtYear.Text);
  CC := StrToInt(edtCC.Text);
  Stroke := StrToInt(edtStroke.Text);
  Name := edtName.Text;
  Model := edtModel.Text;

  NewBike.Create(Price, Stroke, Year, CC, Name, Model);

我查看了这篇文章:Delphi strange inaccessible value (acess violation) o.O并说我必须将项目设置编辑为:

调试信息:开启

本地符号:开启

优化:关闭。

我做了重建,仍然没有改变。我已经离开了重启我的电脑无济于事

1 个答案:

答案 0 :(得分:3)

更改

NewBike.Create(Price, Stroke, Year, CC, Name, Model);

NewBike := MyBike.Create(Price, Stroke, Year, CC, Name, Model);

这是对一个新类实例进行鬃毛的正确方法。

当你创建一个类的新实例时,你在类(MyBike)上调用构造函数,并将它的retun值赋给变量NewBike := MyBike.Create( ...);`

在每个对象(类的实例)中,您有一个名为Self的隐藏参数Delphi Basics上的更多信息。你的案例中的问题是你没有创建一个新的类实例,因此你的自变量是 nil