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

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

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

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

The name of the variable being declaredshall not appear in the initializer expression. This use of auto is allowed when declaring variables in ablock (6.3), in namespace scope (3.3.6), and in a for-init-statement (6.5.3). auto shall appear as one ofthe decl-specifiers in the decl-specifier-seq and the decl-specifier-seq shall be followed by one or more initdeclarators, each of which shall have a non-empty initializer.[ Example:auto x = 5;const auto *v = &x, u = 6;static auto y = 0.0;auto int r;////////OK: x has type intOK: v has type const int*, u has type const intOK: y has type doubleerror: auto is not a storage-class-specifier— end example ]4The auto type-specifier can also be used in declaring a variable in the condition of a selection statement (6.4) oran iteration statement (6.5), in the type-specifier-seq in the new-type-id or type-id of a new-expression (5.3.4), ina for-range-declaration, and in declaring a static data member with a brace-or-equal-initializer that appearswithin the member-specification of a class definition (9.4.2).5A program that uses auto in a context not explicitly allowed in this section is ill-formed.6Once the type of a declarator-id has been determined according to 8.3, the type of the declared variableusing the declarator-id is determined from the type of its initializer using the rules for template argumentdeduction.

Let T be the type that has been determined for a variable identifier d. Obtain P from T byreplacing the occurrences of auto with either a new invented type template parameter U or, if the initializeris a braced-init-list (8.5.4), with std::initializer_list<U>. The type deduced for the variable d is thenthe deduced A determined using the rules of template argument deduction from a function call (14.8.2.1),where P is a function template parameter type and the initializer for d is the corresponding argument. Ifthe deduction fails, the declaration is ill-formed. [ Example:auto x1 = { 1, 2 };auto x2 = { 1, 2.0 };// decltype(x1) is std::initializer_list<int>// error: cannot deduce element type— end example ]7If the list of declarators contains more than one declarator, the type of each declared variable is determinedas described above.

If the type deduced for the template parameter U is not the same in each deduction, theprogram is ill-formed.[ Example:const auto &i = expr;The type of i is the deduced type of the parameter u in the call f(expr) of the following invented functiontemplate:template <class U> void f(const U& u);— end example ]7.21Enumeration declarations[dcl.enum]An enumeration is a distinct type (3.9.2) with named constants. Its name becomes an enum-name, withinits scope.enum-name:identifier§ 7.2© ISO/IEC 2011 – All rights reserved157ISO/IEC 14882:2011(E)enum-specifier:enum-head { enumerator-listopt }enum-head { enumerator-list , }enum-head:enum-key attribute-specifier-seqopt identifieropt enum-baseoptenum-key attribute-specifier-seqopt nested-name-specifier identifierenum-baseoptopaque-enum-declaration:enum-key attribute-specifier-seqopt identifier enum-baseopt ;enum-key:enumenum classenum structenum-base:: type-specifier-seqenumerator-list:enumerator-definitionenumerator-list , enumerator-definitionenumerator-definition:enumeratorenumerator = constant-expressionenumerator:identifierThe optional attribute-specifier-seq in the enum-head and the opaque-enum-declaration appertains to theenumeration; the attributes in that attribute-specifier-seq are thereafter considered attributes of the enumeration whenever it is named.2The enumeration type declared with an enum-key of only enum is an unscoped enumeration, and its enumerators are unscoped enumerators.

The enum-keys enum class and enum struct are semantically equivalent;an enumeration type declared with one of these is a scoped enumeration, and its enumerators are scopedenumerators. The optional identifier shall not be omitted in the declaration of a scoped enumeration. Thetype-specifier-seq of an enum-base shall name an integral type; any cv-qualification is ignored. An opaqueenum-declaration declaring an unscoped enumeration shall not omit the enum-base. The identifiers in anenumerator-list are declared as constants, and can appear wherever constants are required.

An enumeratordefinition with = gives the associated enumerator the value indicated by the constant-expression. If the firstenumerator has no initializer, the value of the corresponding constant is zero. An enumerator-definitionwithout an initializer gives the enumerator the value obtained by increasing the value of the previous enumerator by one.[ Example:enum { a, b, c=0 };enum { d, e, f=e+2 };defines a, c, and d to be zero, b and e to be 1, and f to be 3. — end example ]3An opaque-enum-declaration is either a redeclaration of an enumeration in the current scope or a declarationof a new enumeration.

[ Note: An enumeration declared by an opaque-enum-declaration has fixed underlyingtype and is a complete type. The list of enumerators can be provided in a later redeclaration with an enumspecifier. — end note ] A scoped enumeration shall not be later redeclared as unscoped or with a differentunderlying type. An unscoped enumeration shall not be later redeclared as scoped and each redeclarationshall include an enum-base specifying the same underlying type as in the original declaration.§ 7.2158© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)4If the enum-key is followed by a nested-name-specifier, the enum-specifier shall refer to an enumeration thatwas previously declared directly in the class or namespace to which the nested-name-specifier refers (i.e.,neither inherited nor introduced by a using-declaration), and the enum-specifier shall appear in a namespaceenclosing the previous declaration.5Each enumeration defines a type that is different from all other types.

Each enumeration also has anunderlying type. The underlying type can be explicitly specified using enum-base; if not explicitly specified,the underlying type of a scoped enumeration type is int. In these cases, the underlying type is said to befixed. Following the closing brace of an enum-specifier, each enumerator has the type of its enumeration.

Ifthe underlying type is fixed, the type of each enumerator prior to the closing brace is the underlying typeand the constant-expression in the enumerator-definition shall be a converted constant expression of theunderlying type (5.19); if the initializing value of an enumerator cannot be represented by the underlyingtype, the program is ill-formed.

If the underlying type is not fixed, the type of each enumerator is the typeof its initializing value:— If an initializer is specified for an enumerator, the initializing value has the same type as the expressionand the constant-expression shall be an integral constant expression (5.19).— If no initializer is specified for the first enumerator, the initializing value has an unspecified integraltype.— Otherwise the type of the initializing value is the same as the type of the initializing value of thepreceding enumerator unless the incremented value is not representable in that type, in which case thetype is an unspecified integral type sufficient to contain the incremented value.

If no such type exists,the program is ill-formed.6For an enumeration whose underlying type is not fixed, the underlying type is an integral type that canrepresent all the enumerator values defined in the enumeration. If no integral type can represent all theenumerator values, the enumeration is ill-formed. It is implementation-defined which integral type is usedas the underlying type except that the underlying type shall not be larger than int unless the value of anenumerator cannot fit in an int or unsigned int.

If the enumerator-list is empty, the underlying type isas if the enumeration had a single enumerator with value 0.7For an enumeration whose underlying type is fixed, the values of the enumeration are the values of theunderlying type. Otherwise, for an enumeration where emin is the smallest enumerator and emax is thelargest, the values of the enumeration are the values in the range bmin to bmax , defined as follows: Let Kbe 1 for a two’s complement representation and 0 for a one’s complement or sign-magnitude representation.bmax is the smallest value greater than or equal to max(|emin | − K, |emax |) and equal to 2M − 1, whereM is a non-negative integer.

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

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

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

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