Главная » Просмотр файлов » Стандарт C++ 98

Стандарт C++ 98 (1119566), страница 45

Файл №1119566 Стандарт C++ 98 (Стандарт C++ 98) 45 страницаСтандарт C++ 98 (1119566) страница 452019-05-09СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 45)

It introduces the classname into the current scope. [Example:struct s { int a; };void g(){struct s;s* p;struct s { char* p; };struct s;// hide global struct s// with a local declaration// refer to local struct s// define local struct s// redeclaration, has no effect}—end example] [Note: Such declarations allow definition of classes that refer to each other. [Example:150© ISO/IECISO/IEC 14882:1998(E)9 Classes9.1 Class namesclass Vector;class Matrix {// ...friend Vector operator*(Matrix&, Vector&);};class Vector {// ...friend Vector operator*(Matrix&, Vector&);};Declaration of friends is described in 11.4, operator functions in 13.5.

] ]3An elaborated-type-specifier (7.1.5.3) can also be used as a type-specifier as part of a declaration. It differsfrom a class declaration in that if a class of the elaborated name is in scope the elaborated name will refer toit. [Example:struct s { int a; };void g(int s){struct s* p = new struct s;p->a = s;}// global s// local s—end example]4[Note: The declaration of a class name takes effect immediately after the identifier is seen in the class definition or elaborated-type-specifier. For example,class A * A;first specifies A to be the name of a class and then redefines it as the name of a pointer to an object of thatclass. This means that the elaborated form class A must be used to refer to the class.

Such artistry withnames can be confusing and is best avoided. ]5A typedef-name (7.1.3) that names a class is a class-name, but shall not be used in an elaborated-typespecifier; see also 7.1.3.9.2 Class members[class.mem]member-specification:member-declaration member-specificationoptaccess-specifier : member-specificationoptmember-declaration:decl-specifier-seqopt member-declarator-listopt ;function-definition ;opt::opt nested-name-specifier templateopt unqualified-id ;using-declarationtemplate-declarationmember-declarator-list:member-declaratormember-declarator-list , member-declaratormember-declarator:declarator pure-specifieroptdeclarator constant-initializeroptidentifieropt : constant-expression151ISO/IEC 14882:1998(E)9.2 Class members© ISO/IEC9 Classespure-specifier:= 0constant-initializer:= constant-expression1The member-specification in a class definition declares the full set of members of the class; no member canbe added elsewhere.

Members of a class are data members, member functions (9.3), nested types, and enumerators. Data members and member functions are static or nonstatic; see 9.4. Nested types are classes(9.1, 9.7) and enumerations (7.2) defined in the class, and arbitrary types declared as members by use of atypedef declaration (7.1.3). The enumerators of an enumeration (7.2) defined in the class are members ofthe class. Except when used to declare friends (11.4) or to introduce the name of a member of a base classinto a derived class (7.3.3,11.3), member-declarations declare members of the class, and each suchmember-declaration shall declare at least one member name of the class. A member shall not be declaredtwice in the member-specification, except that a nested class or member class template can be declared andthen later defined.2A class is considered a completely-defined object type (3.9) (or complete type) at the closing } of theclass-specifier.

Within the class member-specification, the class is regarded as complete within functionbodies, default arguments and constructor ctor-initializers (including such things in nested classes). Otherwise it is regarded as incomplete within its own class member-specification.3[Note: a single name can denote several function members provided their types are sufficiently different(clause 13).

]4A member-declarator can contain a constant-initializer only if it declares a static member (9.4) of integral or enumeration type, see 9.4.2.5A member can be initialized using a constructor; see 12.1. [Note: see clause 12 for a description of constructors and other special member functions. ]6A member shall not be auto, extern, or register.7The decl-specifier-seq is omitted in constructor, destructor, and conversion function declarations only. Themember-declarator-list can be omitted only after a class-specifier, an enum-specifier, or a decl-specifierseq of the form friend elaborated-type-specifier. A pure-specifier shall be used only in the declarationof a virtual function (10.3).8Non-static (9.4) members that are class objects shall be objects of previously defined classes.

In particular, a class cl shall not contain an object of class cl, but it can contain a pointer or reference to an objectof class cl. When an array is used as the type of a nonstatic member all dimensions shall be specified.9Except when used to form a pointer to member (5.3.1), when used in the body of a nonstatic member function of its class or of a class derived from its class (9.3.1), or when used in a mem-initializer for a constructor for its class or for a class derived from its class (12.6.2), a nonstatic data or function member of a classshall only be referred to with the class member access syntax (5.2.5).10[Note: the type of a nonstatic member function is an ordinary function type, and the type of a nonstatic datamember is an ordinary object type.

There are no special member function types or data member types. ]11[Example: A simple example of a class definition isstruct tnode {char tword[20];int count;tnode *left;tnode *right;};which contains an array of twenty characters, an integer, and two pointers to similar structures.

Once thisdefinition has been given, the declaration152© ISO/IECISO/IEC 14882:1998(E)9 Classes9.2 Class memberstnode s, *sp;declares s to be a tnode and sp to be a pointer to a tnode. With these declarations, sp->count refersto the count member of the structure to which sp points; s.left refers to the left subtree pointer ofthe structure s; and s.right->tword[0] refers to the initial character of the tword member of theright subtree of s. ]12Nonstatic data members of a (non-union) class declared without an intervening access-specifier are allocated so that later members have higher addresses within a class object.

The order of allocation of nonstaticdata members separated by an access-specifier is unspecified (11.1). Implementation alignment requirements might cause two adjacent members not to be allocated immediately after each other; so mightrequirements for space for managing virtual functions (10.3) and virtual base classes (10.1).13If T is the name of a class, then each of the following shall have a name different from T:— every data member of class T;— every member of class T that is itself a type;— every enumerator of every member of class T that is an enumerated type; and— every member of every anonymous union that is a member of class T.14Two POD-struct (clause 9) types are layout-compatible if they have the same number of members, and corresponding members (in order) have layout-compatible types (3.9).15Two POD-union (clause 9) types are layout-compatible if they have the same number of members, and corresponding members (in any order) have layout-compatible types (3.9).16If a POD-union contains two or more POD-structs that share a common initial sequence, and if the PODunion object currently contains one of these POD-structs, it is permitted to inspect the common initial partof any of them.

Two POD-structs share a common initial sequence if corresponding members have layoutcompatible types (and, for bit-fields, the same widths) for a sequence of one or more initial members.17A pointer to a POD-struct object, suitably converted using a reinterpret_cast, points to its initialmember (or if that member is a bit-field, then to the unit in which it resides) and vice versa. [Note: Theremight therefore be unnamed padding within a POD-struct object, but not at its beginning, as necessary toachieve appropriate alignment.

]9.3 Member functions[class.mfct]1Functions declared in the definition of a class, excluding those declared with a friend specifier (11.4),are called member functions of that class. A member function may be declared static in which case it isa static member function of its class (9.4); otherwise it is a nonstatic member function of its class (9.3.1,9.3.2).2A member function may be defined (8.4) in its class definition, in which case it is an inline member function (7.1.2), or it may be defined outside of its class definition if it has already been declared but notdefined in its class definition. A member function definition that appears outside of the class definitionshall appear in a namespace scope enclosing the class definition. Except for member function definitionsthat appear outside of a class definition, and except for explicit specializations of template member functions (14.7) appearing outside of the class definition, a member function shall not be redeclared.3An inline member function (whether static or nonstatic) may also be defined outside of its class definition provided either its declaration in the class definition or its definition outside of the class definitiondeclares the function as inline.

[Note: member functions of a class in namespace scope have externallinkage. Member functions of a local class (9.8) have no linkage. See 3.5. ]4There shall be at most one definition of a non-inline member function in a program; no diagnostic isrequired. There may be more than one inline member function definition in a program. See 3.2 and7.1.2.153ISO/IEC 14882:1998(E)© ISO/IEC9.3 Member functions59 ClassesIf the definition of a member function is lexically outside its class definition, the member function nameshall be qualified by its class name using the :: operator. [Note: a name used in a member function definition (that is, in the parameter-declaration-clause including the default arguments (8.3.6), or in the memberfunction body, or, for a constructor function (12.1), in a mem-initializer expression (12.6.2)) islooked up as described in 3.4.

Характеристики

Тип файла
PDF-файл
Размер
2,05 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов учебной работы

Свежие статьи
Популярно сейчас
Почему делать на заказ в разы дороже, чем купить готовую учебную работу на СтудИзбе? Наши учебные работы продаются каждый год, тогда как большинство заказов выполняются с нуля. Найдите подходящий учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6418
Авторов
на СтудИзбе
307
Средний доход
с одного платного файла
Обучение Подробнее