我开始使用面向对象的方法来探索 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.