delphi声明类及其调用方法

{type放在interface下的uses引用单元下面}
1
// 声明类 2 type 3 TMyclass = class //注意这里不能加';' 因为这是个整体 4 data: integer; //类的域 5 procedure ChangeData(Value: integer); // 类的方法(过程)按住Ctrl + shift + c键自动生成函数体 6 function GetData:integer; //类的方法(函数) 7 // 类的域和方法可以根据自己的需要添加 8 end; 9 10 { TMyclass } 11 procedure TMyclass.ChangeData(Value: integer); 12 begin 13 Data := Value; // 14 end; 15 16 function TMyclass.GetData: integer; 17 begin 18 result := Data; 19 end; 20 21 // 访问类 22 procedure TForm1.SpeedButton2Click(Sender: TObject); 23 var 24 Myclass: TMyclass; 25 i: integer; 26 begin 27 try 28 myclass := TMyclass.Create; // 使用前一定要实例化,不然不能用 29 myclass.ChangeData(12); // 给类的方法赋值, 30 i := myclass.GetData; // 获取类中 31 showMessage(IntToStr(i)); // {12} 32 finally 33 myclass.Free; // 最后需要将使用过的内存释放 34 end; 35 end;

另外,类中还存在两种特殊的方法,分别构造方法(Constructor)和析构方法(Destructor)。
类就是面向对象的思想。

posted @ 2015-08-30 22:40  王云盼  阅读(802)  评论(0编辑  收藏  举报