Delphi protected что это
Delphi protected что это
Опытный
Профиль
Группа: Участник
Сообщений: 557
Регистрация: 5.7.2008
Где: Прибалтика
Репутация: 1
Всего: 6
Опытный
Профиль
Группа: Участник
Сообщений: 602
Регистрация: 13.1.2007
Репутация: 22
Всего: 50
Цитата(wikipedia) |
TMyClass = class(TObject) private <Описанные в этой секции элементы не доступны извне (за пределами класса).> <Здесь обычно находятся поля класса.> protected <Описанные в этой секции элементы доступны только классу и всем его потомкам.> public <Описанные в этой секции элементы доступны всем.> published <Описанные в этой секции элементы доступны всем и отображаются в Object Inspector'e.> end; |
Профиль
Группа: Админ
Сообщений: 3639
Регистрация: 31.7.2007
Где: Moscow, Dubai
Репутация: 50
Всего: 372
Это все секции класса.
Опытный
Профиль
Группа: Участник
Сообщений: 557
Регистрация: 5.7.2008
Где: Прибалтика
Репутация: 1
Всего: 6
Inspired =)
Профиль
Группа: Экс. модератор
Сообщений: 1535
Регистрация: 7.5.2005
Репутация: 18
Всего: 191
public
Все члены класса, расположенные здесь, доступны из любой точки программы. Обычно здесь располагаются свойства и методы для использования класса непосредственно по назначению. Могут быть и абстрактные методы.
) помещаются в эту секцию.
protected
От private отличается тем, что члены класса доступны и любому из его потомков, даже если последний объявлен в другом модуле.
Обычно здесь методы в перспективе на модифицирование, чтобы менять поведение класса (часто виртуальные и динамические), а также готовые методы, которые мог бы использовать класс-потомок, дополняя свою внутреннюю реализацию. Также могут быть и абстрактные методы.
published
Область видимости как у секции public. Но, помимо прочего, эти свойства будут доступны в Инспекторе Объектов для изменения. При «авто-завершении» (auto-complete) класса средой Delphi все свойства и методы, которые были объявлены вне какой-либо секции, помещаются сюда.
automated
Редко используемая секция. Члены здесь разрешается размещать, если класс унаследован от класса TAutoObject, чтобы создавать сервера автоматизации. Область видимости как и у public. Эта секция имеет ограничения на дефиниции свойств и методов из-за направленности на технологию COM.
strict protected
Члены класса видны только классу и его потомкам.
Доступ к сгенерированной информации (п. 3 и 4) осуществялется через таблицу VMT (это по сути поле класса, но оно всегда скрыто, и всегда первое по счету) класса (по отрицательным смещениям).
Секции могут дублироваться по именам (их может дублировать и среда Delphi при «авто-завершении» класса).
Опытный
Профиль
Группа: Участник
Сообщений: 557
Регистрация: 5.7.2008
Где: Прибалтика
Репутация: 1
Всего: 6
Старательный
Профиль
Группа: Участник
Сообщений: 223
Регистрация: 19.10.2006
Где: Молдова
Репутация: нет
Всего: 6
Можно еще кое-что уточнить по поводу «private, public, published, protected»?
Область видимости процедур (функций, переменных. ), находящихся в этих секциях, уже объяснили. То есть программист, в зависимости от своих задач, помещает объявление процедуры в нужную секцию. А как быть с процедурами, которые появляются в коде после, например, двойного щелчка по кнопке (procedure Button1Click(Sender: TObject);)? Их объявления автоматически появляются выше всех секций. Куда относятся эти процедуры, какая у них видимость?
Эксперт
Профиль
Группа: Участник
Сообщений: 1108
Регистрация: 6.10.2006
Репутация: 10
Всего: 80
Цитата(Rrader @ 1.9.2008, 14:43 |
1) Секция без названия у класса вашей формы, унаследованного по умолчанию от TForm, обслуживается Delphi. Но область её видимости не private, а published |
Старательный
Профиль
Группа: Участник
Сообщений: 223
Регистрация: 19.10.2006
Где: Молдова
Репутация: нет
Всего: 6
Старательный
Профиль
Группа: Участник
Сообщений: 223
Регистрация: 19.10.2006
Где: Молдова
Репутация: нет
Всего: 6
1. Публиковать ссылки на вскрытые компоненты 2. Обсуждать взлом компонентов и делиться вскрытыми компонентами Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, Snowy, MetalFan, bems, Poseidon, Rrader.
[ Время генерации скрипта: 0.1307 ] [ Использовано запросов: 21 ] [ GZIP включён ] Classes and Objects (Delphi)This topic covers the following material: ContentsClass TypesA class, or class type, defines a structure consisting of fields, methods, and properties. Instances of a class type are called objects. The fields, methods, and properties of a class are called its components or members. Objects are dynamically allocated blocks of memory whose structure is determined by their class type. Each object has a unique copy of every field defined in the class, but all instances of a class share the same methods. Objects are created and destroyed by special methods called constructors and destructors. A class type must be declared and given a name before it can be instantiated. (You cannot define a class type within a variable declaration.) Declare classes only in the outermost scope of a program or unit, not in a procedure or function declaration. A class type declaration has the following form: Required elements of the class type declaration Optional elements of the class type declaration Methods appear in a class declaration as function or procedure headings, with no body. Defining declarations for each method occur elsewhere in the program. For example, here is the declaration of the TMemoryStream class from the Classes unit: Given this declaration, you can create an instance of TMemoryStream as follows: Inheritance and ScopeWhen you declare a class, you can specify its immediate ancestor. For example: declares a class called TSomeControl that descends from Vcl.Controls.TControl. A class type automatically inherits all of the members from its immediate ancestor. Each class can declare new members and can redefine inherited ones, but a class cannot remove members defined in an ancestor. Hence TSomeControl contains all of the members defined in Vcl.Controls.TControl and in each of the Vcl.Controls.TControl ancestors. The scope of a member’s identifier starts at the point where the member is declared, continues to the end of the class declaration, and extends over all descendants of the class and the blocks of all methods defined in the class and its descendants. TObject and TClassThe System.TObject class, declared in the System unit, is the ultimate ancestor of all other classes. System.TObject defines only a handful of methods, including a basic constructor and destructor. In addition to System.TObject, the System unit declares the class reference type System.TClass: If the declaration of a class type does not specify an ancestor, the class inherits directly from System.TObject. Thus: The latter form is recommended for readability. Compatibility of Class TypesA class type is assignment-compatible with its ancestors. Hence a variable of a class type can reference an instance of any descendant type. For example, given the declarations: Object TypesThe Delphi compiler allows an alternative syntax to class types. You can declare object types using the syntax: where objectTypeName is any valid identifier, (ancestorObjectType) is optional, and memberList declares fields, methods, and properties. If (ancestorObjectType) is omitted, then the new type has no ancestor. Object types cannot have published members. Since object types do not descend from System.TObject, they provide no built-in constructors, destructors, or other methods. You can create instances of an object type using the New procedure and destroy them with the Dispose procedure, or you can simply declare variables of an object type, just as you would with records. Object types are supported for backward compatibility only. Their use is not recommended. Visibility of Class MembersEvery member of a class has an attribute called visibility, which is indicated by one of the reserved words private, protected, public, published, or automated. For example, If a member’s declaration appears without its own visibility specifier, the member has the same visibility as the one that precedes it. Members at the beginning of a class declaration that do not have a specified visibility are by default published, provided the class is compiled in the <$M+>state or is derived from a class compiled in the <$M+>state; otherwise, such members are public. For readability, it is best to organize a class declaration by visibility, placing all the private members together, followed by all the protected members, and so forth. This way each visibility reserved word appears at most once and marks the beginning of a new ‘section’ of the declaration. So a typical class declaration should be like this: You can increase the visibility of a property in a descendent class by redeclaring it, but you cannot decrease its visibility. For example, a protected property can be made public in a descendant, but not private. Moreover, published properties cannot become public in a descendent class. For more information, see Property Overrides and Redeclarations. Private, Protected, and Public MembersA private member is invisible outside of the unit or program where its class is declared. In other words, a private method cannot be called from another module, and a private field or property cannot be read or written to from another module. By placing related class declarations in the same module, you can give each class access to the private members of another class without making those members more widely accessible. For a member to be visible only inside its class, it needs to be declared strict private. A protected member is visible anywhere in the module where its class is declared and from any descendent class, regardless of the module where the descendent class appears. A protected method can be called, and a protected field or property read or written to, from the definition of any method belonging to a class that descends from the one where the protected member is declared. Members that are intended for use only in the implementation of derived classes are usually protected. A public member is visible wherever its class can be referenced. Strict Visibility SpecifiersIn addition to private and protected visibility specifiers, the Delphi compiler supports additional visibility settings with greater access constraints. These settings are strict private and strict protected visibility. Class members with strict private visibility are accessible only within the class in which they are declared. They are not visible to procedures or functions declared within the same unit. Class members with strict protected visibility are visible within the class in which they are declared, and within any descendent class, regardless of where it is declared. Furthermore, when instance members (those declared without the class or class var keywords) are declared strict private or strict protected, they are inaccessible outside of the instance of a class in which they appear. An instance of a class cannot access strict private or strict protected instance members in other instances of the same class. Published MembersPublished members have the same visibility as public members. The difference is that run-time type information (RTTI) is generated for published members. RTTI allows an application to query the fields and properties of an object dynamically and to locate its methods. RTTI is used to access the values of properties when saving and loading form files, to display properties in the Object Inspector, and to associate specific methods (called event handlers) with specific properties (called events). Published properties are restricted to certain data types. Ordinal, string, class, interface, variant, and method-pointer types can be published. So can set types, provided the upper and lower bounds of the base type have ordinal values from 0 through 31. (In other words, the set must fit in a byte, word, or double word.) Any real type except Real48 can be published. Properties of an array type (as distinct from array properties, discussed below) cannot be published. Some properties, although publishable, are not fully supported by the streaming system. These include properties of record types, array properties of all publishable types, and properties of enumerated types that include anonymous values. If you publish a property of this kind, the Object Inspector will not display it correctly, nor will the property’s value be preserved when objects are streamed to disk. All methods are publishable, but a class cannot publish two or more overloaded methods with the same name. Fields can be published only if they are of a class or interface type. Automated Members (Win32 Only)The following restrictions apply to methods and properties declared as automated. The declaration of an automated method or property can include a dispid directive. Specifying an already used ID in a dispid directive causes an error. On the Win32 platform, this directive must be followed by an integer constant that specifies an Automation dispatch ID for the member. Otherwise, the compiler automatically assigns the member a dispatch ID that is one larger than the largest dispatch ID used by any method or property in the class and its ancestors. For more information about Automation (on Win32 only), see Automation Objects. Forward Declarations and Mutually Dependent ClassesIf the declaration of a class type ends with the word class and a semicolon—that is, if it has the form with no ancestor or class members listed after the word class, then it is a forward declaration. A forward declaration must be resolved by a defining declaration of the same class within the same type declaration section. In other words, between a forward declaration and its defining declaration, nothing can occur except other type declarations. Forward declarations allow mutually dependent classes. For example: Справочник функций и процедур Delphi: Protected | ||||||
Protected Деректива | Начинает раздел класса частных данных доступных подклассам | unit |
type Class declaration Protected Field | Property | Method declaration <. > end; |
|