我开始用面向对象的方法探索Pascal。 我想知道当前对象是否有 this
或self
引用?我一直在寻找文件,但我没有找到答案。
修改
通过反复试验,我发现您可以使用self
。现在我的问题是,如果没有编译器抛出“重复标识符错误”,我可以实现(下面的代码段)吗?
constructor Employee.create(name:String; salary:Real);
begin
self.name := name;
self.salary := salary;
end;
我在下面有一个程序,可以创建2名员工并显示他们的信息
{$mode objfpc} // directive to be used for defining classes
{$m+} // directive to be used for using constructor
program EmployeeTest;
type
Employee = class
private
name:String;
salary:Real;
public
constructor create(name:String; salary:Real);
procedure setName(name:String);
function getName():String;
procedure setSalary(salary:Real);
function getSalary():Real;
procedure displayEmployee;
end;
var empl1,empl2:Employee;
constructor Employee.create(name:String; salary:Real);
begin
setName(name);
setSalary(salary);
end;
procedure Employee.setName(name:String);
begin
self.name := name;
end;
procedure Employee.setSalary(salary:Real);
begin
self.salary := salary;
end;
function Employee.getName():String;
begin
getName := self.name;
end;
function Employee.getSalary():Real;
begin
getSalary := self.salary;
end;
procedure Employee.displayEmployee;
begin
writeln('Name: ',getName,', Salary: $',getSalary:0:2);
end;
begin
empl1 := Employee.create('Bob', 75000);
empl2 := Employee.create('Joe', 50000);
empl1.displayEmployee();
empl2.displayEmployee();
readln; {pause}
end.
答案 0 :(得分:3)
答案 1 :(得分:2)
以下是您班级的示例:
type
TEmployee = class(TObject)
private
FName: String;
FSalary:Real;
public
constructor Create(AName:String; ASalary:Real);
property Name: String read FName write FName;
property Salary: Real read FSalary write FSalary;
procedure DisplayEmployee;
end;
constructor TEmployee.Create(AName:String; ASalary:Real);
begin
inherited Create;
FName := AName;
FSalary := ASalary;
end;
procedure TEmployee.DisplayEmployee;
begin
WriteLn('Name: ', FName, ', Salary: $', FSalary:0:2);
end;