Delphi and enum
Does Delp开发者_开发百科hi have an analog of enum in C?
Yes, Delphi has the following enumerated type construction:
type
TDigits = (dgOne, dgTwo, dgThree <etc>);
Also, like in C, each symbol of an enumerated type may have a specified value, like this:
type
TDigits = (dgOne = 1, dgTwo, dgThree <etc>);
Yes. Check out the first portion of Delphi Basics: Enumerations, SubRanges, and Sets.
Have a look at
Enumerations, SubRanges and Sets
In addition to the positive responses that are focused on the parallels, there are
Some restrictions:
1. Anonymous enumerations are not supported in Delphi.
So you have to translate
enum { SOME_CONSTANT = 42 };
into
const
SOME_CONSTANT = 42
… which is, by the way, a better wording for your actual intent. But unfortunately, this can be translated back into something different. At least C++Builder 6 translates it like this in the auto-generated *.hpp
file:
static const Shortint SOME_CONSTANT = 0x2A;
2. Explicit enum values were added with Delphi 6.
The feature of explicitly adding values to enumerators was introduced with Delphi 6. So you have to switch to normal constants, see this answer to How to create an enum with explicit values in Delphi 5 for more.
3. Finally, a restriction of C:
In C, enumerations are just compile-time constants that are implicitly converted into int
as needed. This is basically where the support ends. Delphi has a stronger typing but provides information about the valid range and also iteration, see this snippet:
procedure TForm1.Button1Click(Sender: TObject);
type
TMyEnum = (meOne, meTwo, meThree);
var
v: TMyEnum;
txt: String;
begin
for v := Low(TMyEnum) to High(TMyEnum) do
txt := txt + IntToStr(Integer(v)) + ' ';
ShowMessage(txt)
end;
精彩评论