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

Стандарт C++ 11 (1119564), страница 65

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

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

Their layout is specified in 9.2. — end note ]10A POD struct 109 is a non-union class that is both a trivial class and a standard-layout class, and has nonon-static data members of type non-POD struct, non-POD union (or array of such types).

Similarly, aPOD union is a union that is both a trivial class and a standard layout class, and has no non-static datamembers of type non-POD struct, non-POD union (or array of such types). A POD class is a class that iseither a POD struct or a POD union.[ Example:struct N {int i;int j;virtual ~N();};// neither trivial nor standard-layoutstruct T {int i;private:int j;};// trivial but not standard-layoutstruct SL {int i;int j;// standard-layout but not trivial108) This ensures that two subobjects that have the same class type and that belong to the same most derived object are notallocated at the same address (5.10).109) The acronym POD stands for “plain old data”.© ISO/IEC 2011 – All rights reserved217ISO/IEC 14882:2011(E)~SL();};struct POD {int i;int j;};// both trivial and standard-layout— end example ]11If a class-head-name contains a nested-name-specifier, the class-specifier shall refer to a class that waspreviously declared directly in the class or namespace to which the nested-name-specifier refers, or in anelement of the inline namespace set (7.3.1) of that namespace (i.e., not merely inherited or introduced bya using-declaration), and the class-specifier shall appear in a namespace enclosing the previous declaration.In such cases, the nested-name-specifier of the class-head-name of the definition shall not begin with adecltype-specifier.9.11Class names[class.name]A class definition introduces a new type.

[ Example:struct X { int a; };struct Y { int a; };X a1;Y a2;int a3;declares three variables of three different types. This implies thata1 = a2;a1 = a3;// error: Y assigned to X// error: int assigned to Xare type mismatches, and thatint f(X);int f(Y);declare an overloaded (Clause 13) function f() and not simply a single function f() twice. For the samereason,struct S { int a; };struct S { int a; };// error, double definitionis ill-formed because it defines S twice. — end example ]2A class declaration introduces the class name into the scope where it is declared and hides any class, variable,function, or other declaration of that name in an enclosing scope (3.3). If a class name is declared in a scopewhere a variable, function, or enumerator of the same name is also declared, then when both declarationsare in scope, the class can be referred to only using an elaborated-type-specifier (3.4.4).

[ Example:struct stat {// ...};stat gstat;// use plain stat to// define variable§ 9.1218© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)int stat(struct stat*);void f() {struct stat* ps;stat(ps);// redeclare stat as function// struct prefix needed// to name struct stat// call stat()}— end example ] A declaration consisting solely of class-key identifier; is either a redeclaration of the namein the current scope or a forward declaration of the identifier as a class name. It introduces the class nameinto the current scope.

[ Example:struct s { int a; };void g() {struct s;s* p;struct s { char* p; };struct s;//////////hide global struct swith a block-scope declarationrefer to local struct sdefine local struct sredeclaration, has no effect}— end example ] [ Note: Such declarations allow definition of classes that refer to each other. [ Example:class Vector;class Matrix {// ...friend Vector operator*(const Matrix&, const Vector&);};class Vector {// ...friend Vector operator*(const Matrix&, const Vector&);};Declaration of friends is described in 11.3, operator functions in 13.5. — end example ] — end note ]3[ Note: An elaborated-type-specifier (7.1.6.3) can also be used as a type-specifier as part of a declaration.

Itdiffers from a class declaration in that if a class of the elaborated name is in scope the elaborated name willrefer to it. — end note ] [ Example:struct s { int a; };void g(int s) {struct s* p = new struct s;p->a = s;}// global s// parameter s— end example ]4[ Note: The declaration of a class name takes effect immediately after the identifier is seen in the classdefinition or elaborated-type-specifier. For example,class A * A;§ 9.1© ISO/IEC 2011 – All rights reserved219ISO/IEC 14882:2011(E)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. — end note ]5A typedef-name (7.1.3) that names a class type, or a cv-qualified version thereof, is also a class-name. If atypedef-name that names a cv-qualified class type is used where a class-name is required, the cv-qualifiersare ignored. A typedef-name shall not be used as the identifier in a class-head.9.2Class members[class.mem]member-specification:member-declaration member-specificationoptaccess-specifier : member-specificationoptmember-declaration:attribute-specifier-seqopt decl-specifier-seqopt member-declarator-listopt ;function-definition ;optusing-declarationstatic_assert-declarationtemplate-declarationalias-declarationmember-declarator-list:member-declaratormember-declarator-list , member-declaratormember-declarator:declarator virt-specifier-seqopt pure-specifieroptdeclarator brace-or-equal-initializeroptidentifieropt attribute-specifier-seqopt : constant-expressionvirt-specifier-seq:virt-specifiervirt-specifier-seq virt-specifiervirt-specifier:overridefinalpure-specifier:= 01The 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, andenumerators. Data members and member functions are static or non-static; see 9.4. Nested types areclasses (9.1, 9.7) and enumerations (7.2) defined in the class, and arbitrary types declared as members byuse of a typedef declaration (7.1.3). The enumerators of an unscoped enumeration (7.2) defined in the classare members of the class. Except when used to declare friends (11.3) or to introduce the name of a memberof a base class into a derived class (7.3.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, and except that an enumeration can be introduced with an opaque-enum-declaration andlater redeclared with an enum-specifier.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, exception-specifications, and brace-or-equal-initializers for non-static data members (including such things in nested classes). Otherwise it is regarded as incomplete within its own classmember-specification.§ 9.2220© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)3[ Note: A single name can denote several function members provided their types are sufficiently different(Clause 13). — end note ]4A member can be initialized using a constructor; see 12.1. [ Note: See Clause 12 for a description ofconstructors and other special member functions.

— end note ]5A member can be initialized using a brace-or-equal-initializer. (For static data members, see 9.4.2; fornon-static data members, see 12.6.2).6A member shall not be declared with the extern or register storage-class-specifier. Within a class definition,a member shall not be declared with the thread_local storage-class-specifier unless also declared static.7The decl-specifier-seq may be omitted in constructor, destructor, and conversion function declarations only;when declaring another kind of member the decl-specifier-seq shall contain a type-specifier that is not a cvqualifier. The member-declarator-list can be omitted only after a class-specifier or an enum-specifier or in afriend declaration (11.3). A pure-specifier shall be used only in the declaration of a virtual function (10.3).8The optional attribute-specifier-seq in a member-declaration appertains to each of the entities declared bythe member-declarators; it shall not appear if the optional member-declarator-list is omitted.9A virt-specifier-seq shall contain at most one of each virt-specifier.

A virt-specifier-seq shall appear only inthe declaration of a virtual member function (10.3).10Non-static (9.4) data members shall not have incomplete types. In particular, a class C shall not containa non-static member of class C, but it can contain a pointer or reference to an object of class C.11[ Note: See 5.1 for restrictions on the use of non-static data members and non-static member functions.— end note ]12[ Note: The type of a non-static member function is an ordinary function type, and the type of a non-staticdata member is an ordinary object type.

There are no special member function types or data member types.— end note ]13[ 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 objects of the same type. Oncethis definition has been given, the declarationtnode s, *sp;declares s to be a tnode and sp to be a pointer to a tnode.

With these declarations, sp->count refers tothe count member of the object to which sp points; s.left refers to the left subtree pointer of the objects; and s.right->tword[0] refers to the initial character of the tword member of the right subtree of s.— end example ]14Nonstatic data members of a (non-union) class with the same access control (Clause 11) are allocated sothat later members have higher addresses within a class object. The order of allocation of non-static datamembers with different access control is unspecified (11). Implementation alignment requirements mightcause two adjacent members not to be allocated immediately after each other; so might requirements forspace for managing virtual functions (10.3) and virtual base classes (10.1).§ 9.2© ISO/IEC 2011 – All rights reserved221ISO/IEC 14882:2011(E)15If T is the name of a class, then each of the following shall have a name different from T:— every static data member of class T;— every member function of class T [ Note: This restriction does not apply to constructors, which do nothave names (12.1) — end note ];— every member of class T that is itself a type;— every enumerator of every member of class T that is an unscoped enumerated type; and— every member of every anonymous union that is a member of class T.16In addition, if class T has a user-declared constructor (12.1), every non-static data member of class T shallhave a name different from T.17Two standard-layout struct (Clause 9) types are layout-compatible if they have the same number of non-staticdata members and corresponding non-static data members (in declaration order) have layout-compatibletypes (3.9).18Two standard-layout union (Clause 9) types are layout-compatible if they have the same number of nonstatic data members and corresponding non-static data members (in any order) have layout-compatibletypes (3.9).19If a standard-layout union contains two or more standard-layout structs that share a common initial sequence,and if the standard-layout union object currently contains one of these standard-layout structs, it is permittedto inspect the common initial part of any of them.

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

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

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

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