delphi 中声明类型变量type放在什么地方?

初学者。按照书上的说法试着声明变量,用type语句如下:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;

type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
type
Tcolor=(red,blue);
var
c: Tcolor ;
c:=red;
end;

end.

怎么系统总是报错 Project1.dpr(5): Could not compile used unit 'Unit1.pas'?
或者你也可以简单的告诉我。type和var怎么用(我按照书上说的做不行)

type 是定义类型
VAR是声明变量

这两个关键字除了不能放在类定义,过程或函数体内外,基乎可以在任何地方,所放地方的不同,那么他们起的作用域不同.
1.类定义,像如
type //告诉编译器,下面的代码定义一个类
Tform1 = class(Tform) //Tform1 从TForm 继承
....//这里是类的一些属性,函数等等
end; //从Tform1 = class(Tform) 到这个end为止即为一个类定义. 在这中间不允许有 type 和 var出现

2.过程或函数体内部
procedure xxxxxxxxxxxxxxxx; //告诉编译器,下面的代码定义一个过程
begin
...............
end;
function XXXXXXXXXXXXXXX;//告诉编译器,下面的代码定义一个函数
begin
...............
end;//上面的两个begin..end 不允许有 type 和 var出现追问

谢谢!
我出现的错误是把type和var放在了begin end里面了是吗?

追答

是的

温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-03-27
procedure TForm1.Button1Click(Sender: TObject);
type
TColor = (Red, Blue);
var
c: TColor;
begin
c := Red;

end;追问

谢谢!

第2个回答  2011-03-27
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;

type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
Tcolor=(red,blue);

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
c: Tcolor ;
begin
c:=red;
end;

end.追问

谢谢啦。那个,能不能给我讲解一下啊?

追答

TForm1 = class(TForm)
这也是定义了一个类,所以后面定义了一个对象var Form1: TForm1;
Tcolor=(red,blue);
类似的也定义了一个类型,可以直接使用。

相似回答