Версия для печати темы

Нажмите сюда для просмотра этой темы в обычном формате

Форум «Всё о Паскале» _ Теоретические вопросы _ Нужно найти любую информацию о "записи".

Автор: Виктор 29.01.2003 10:50

Срочно нужно что-то о "записях". Может быть на вашем сайте есть? Если кто-то знает, пожалуйста помогите, очень сильно надо

Автор: ___ALex___ 29.01.2003 14:25

Лови:
З А П И С И

 Запись представляет собой совокупность ограниченного  числа  логи-
чески связанных компонент,  принадлежащих к разным типам.  Компоненты
записи называются полями, каждое из которых определяется именем. Поле
записи содержит имя поля, вслед за которым через двоеточие указывает-
ся тип этого поля. Поля записи могут относиться к любому типу, допус-
тимому в языке Паскаль, за исключением файлового типа.
  Описание записи   в   языке   ПАСКАЛЬ   осуществляется  с  помощью
служебного слова RECORD,  вслед за которым описываются компоненты за-
писи. Завершается описание записи служебным словом END.
  Например, записная книжка содержит фамилии,  инициалы и номера те-
лефона, поэтому отдельную строку в записной книжке удобно представить
в виде следующей записи:
 
        type   Row=Record
                    FIO: String[20];
                    TEL: String[7]
                   end;
        var    str: Row;

  Описание записей возможно и без использования имени типа,   напри-
мер:
        var  str: Record
                   FIO: String[20];
                   TEL: String[7]
                  end;

  Обращение к записи в целом допускается только в операторах присва-
ивания, где  слева и справа от знака присваивания используются  имена
записей одинакового типа. Во всех остальных случаях оперируют отдель-
ными полями записей.  Чтобы обратиться к отдельной компоненте записи,
необходимо задать  имя записи и через точку указать имя нужного поля,
например:
 
        str.FIO,   str.TEL

  Такое имя называется составным. Компонентой записи может быть так-
же запись,    в таком случае составное имя будет содержать не два,  а
большее количество имен.
  Обращение к  компонентам записей можно упростить,  если воспользо-
ваться оператором присоединения with.
  Он позволяет заменить составные имена,  характеризующие каждое по-
ле, просто на имена полей, а имя записи определить в операторе присо-
единения:
 
        with M do OP;

  Здесь М  -  имя  записи,   ОР  - оператор,  простой или составной.
Оператор ОР представляет собой область действия оператора присоедине-
ния, в пределах которой можно не использовать составные имена.
  Иногда содержимое отдельной записи зависит от значения  одного  из
ее полей.  В языке ПАСКАЛЬ допускается описание записи,  состоящей из
общей и вариантной частей.  Вариантная часть задается с помощью конс-
трукции
        case P of,

где Р - имя  поля из общей  части  записи. Возможные значения, прини-
маемые этим полем,  перечисляются так же, как и в операторе варианта.
Однако вместо указания выполняемого действия, как это делается в опе-
раторе варианта,    указываются поля варианта,  заключенные в круглые
скобки. Описание вариантной части завершается служебным словом end.
  Тип поля Р можно указать в заголовке вариантной части, например:
 
        case P: Integer of
 
  Инициализация записей  осуществляется  с  помощью   типизированных
констант:
 
  type
    RecType= Record
              x,y: Word;
              ch: Char;
              dim: Array[1..3] of Byte
             end;
 
  const
    Rec: RecType= ( x: 127; y: 255;
                    ch: 'A';
                    dim: (2, 4, 8) );

Автор: ___ALex___ 29.01.2003 15:49

вот исчерпывающая информация:

A record type can have a variant part, which looks like a case statement. The variant part must follow the other fields in the record declaration.
To declare a record type with a variant part, use the following syntax.

type recordTypeName = record

 fieldList1: type1;
 ...
 fieldListn: typen;
case tag: ordinalType of
 constantList1: (variant1);
 ...
 constantListn: (variantn);
end;

The first part of the declaration—up to the reserved word case—is the same as that of a standard record type. The remainder of the declaration—from case to the optional final semicolon—is called the variant part. In the variant part,

tag is optional and can be any valid identifier. If you omit tag, omit the colon (smile.gif after it as well.
     ordinalType denotes an ordinal type.
     Each constantList is a constant denoting a value of type ordinalType, or a comma-delimited list of such constants. No value can be represented more than once in the combined constantLists.
     Each variant is a comma-delimited list of declarations resembling the fieldList: type constructions in the main part of the record type. That is, a variant has the form

fieldList1: type1;

...
fieldListn: typen;

where each fieldList is a valid identifier or comma-delimited list of identifiers, each type denotes a type, and the final semicolon is optional. The types must not be long strings, dynamic arrays, variants (that is, Variant types), or interfaces, nor can they be structured types that contain long strings, dynamic arrays, variants, or interfaces; but they can be pointers to these types.

Records with variant parts are complicated syntactically but deceptively simple semantically. The variant part of a record contains several variants which share the same space in memory. You can read or write to any field of any variant at any time; but if you write to a field in one variant and then to a field in another variant, you may be overwriting your own data. The tag, if there is one, functions as an extra field (of type ordinalType) in the non-variant part of the record.

Variant parts have two purposes. First, suppose you want to create a record type that has fields for different kinds of data, but you know that you will never need to use all of the fields in a single record instance. For example,

type

 TEmployee = record
 FirstName, LastName: string[40];
 BirthDate: TDate;
 case Salaried: Boolean of
   True: (AnnualSalary: Currency);
   False: (HourlyWage: Currency);
end;

The idea here is that every employee has either a salary or an hourly wage, but not both. So when you create an instance of TEmployee, there is no reason to allocate enough memory for both fields. In this case, the only difference between the variants is in the field names, but the fields could just as easily have been of different types. Consider some more complicated examples:

type

 TPerson = record
 FirstName, LastName: string[40];
 BirthDate: TDate;
 case Citizen: Boolean of
   True: (Birthplace: string[40]);
   False: (Country: string[20];
           EntryPort: string[20];
           EntryDate, ExitDate: TDate);
 end;

type

 TShapeList = (Rectangle, Triangle, Circle, Ellipse, Other);
 TFigure = record
   case TShapeList of
     Rectangle: (Height, Width: Real);
     Triangle: (Side1, Side2, Angle: Real);
     Circle: (Radius: Real);
     Ellipse, Other: ();
 end;

For each record instance, the compiler allocates enough memory to hold all the fields in the largest variant. The optional tag and the constantLists (like Rectangle, Triangle, and so forth in the last example above) play no role in the way the compiler manages the fields; they are there only for the convenience of the programmer.
The second reason for variant parts is that they let you treat the same data as belonging to different types, even in cases where the compiler would not allow a typecast. For example, if you have a 64-bit Real as the first field in one variant and a 32-bit Integer as the first field in another, you can assign a value to the Real field and then read back the first 32 bits of it as the value of the Integer field (passing it, say, to a function that requires integer parameters).

___________________________________________