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

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

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

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

bmin is zero if emin is non-negative and −(bmax + K) otherwise. The size ofthe smallest bit-field large enough to hold all the values of the enumeration type is max(M, 1) if bmin iszero and M + 1 otherwise. It is possible to define an enumeration that has values not defined by any of itsenumerators. If the enumerator-list is empty, the values of the enumeration are as if the enumeration had asingle enumerator with value 0.938Two enumeration types are layout-compatible if they have the same underlying type.9The value of an enumerator or an object of an unscoped enumeration type is converted to an integer byintegral promotion (4.5).

[ Example:enum color { red, yellow, green=20, blue };color col = red;color* cp = &col;if (*cp == blue)// ...93) This set of values is used to define promotion and conversion semantics for the enumeration type. It does not preclude anexpression of enumeration type from having a value that falls outside this range.§ 7.2© ISO/IEC 2011 – All rights reserved159ISO/IEC 14882:2011(E)makes color a type describing various colors, and then declares col as an object of that type, and cp as apointer to an object of that type. The possible values of an object of type color are red, yellow, green,blue; these values can be converted to the integral values 0, 1, 20, and 21.

Since enumerations are distincttypes, objects of type color can be assigned only values of type color.color c = 1;// error: type mismatch,// no conversion from int to colorint i = yellow;// OK: yellow converted to integral value 1// integral promotionNote that this implicit enum to int conversion is not provided for a scoped enumeration:enum class Col { red, yellow, green };int x = Col::red;// error: no Col to int conversionCol y = Col::red;if (y) { }// error: no Col to bool conversion— end example ]10Each enum-name and each unscoped enumerator is declared in the scope that immediately contains theenum-specifier. Each scoped enumerator is declared in the scope of the enumeration.

These names obey thescope rules defined for all names in (3.3) and (3.4).[ Example:enum direction { left=’l’, right=’r’ };void g() {direction d;d = left;d = direction::right;}// OK// OK// OKenum class altitude { high=’h’, low=’l’ };void h() {altitude a;a = high;a = altitude::low;}// OK// error: high not in scope// OK— end example ] An enumerator declared in class scope can be referred to using the class member accessoperators (::, . (dot) and -> (arrow)), see 5.2.5. [ Example:struct X {enum direction { left=’l’, right=’r’ };int f(int i) { return i==left ? 0 : i==right ? 1 : 2; }};void g(X* p) {direction d;int i;i = p->f(left);i = p->f(X::right);i = p->f(p->left);// ...}// error: direction not in scope// error: left not in scope// OK// OK§ 7.2160© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)— end example ]7.3Namespaces[basic.namespace]1A namespace is an optionally-named declarative region.

The name of a namespace can be used to accessentities declared in that namespace; that is, the members of the namespace. Unlike other declarative regions,the definition of a namespace can be split over several parts of one or more translation units.2The outermost declarative region of a translation unit is a namespace; see 3.3.6.7.3.11Namespace definition[namespace.def ]The grammar for a namespace-definition isnamespace-name:original-namespace-namenamespace-aliasoriginal-namespace-name:identifiernamespace-definition:named-namespace-definitionunnamed-namespace-definitionnamed-namespace-definition:original-namespace-definitionextension-namespace-definitionoriginal-namespace-definition:inlineopt namespace identifier { namespace-body }extension-namespace-definition:inlineopt namespace original-namespace-name { namespace-body }unnamed-namespace-definition:inlineopt namespace { namespace-body }namespace-body:declaration-seqopt2The identifier in an original-namespace-definition shall not have been previously defined in the declarativeregion in which the original-namespace-definition appears.

The identifier in an original-namespace-definitionis the name of the namespace. Subsequently in that declarative region, it is treated as an original-namespacename.3The original-namespace-name in an extension-namespace-definition shall have previously been defined in anoriginal-namespace-definition in the same declarative region.4Every namespace-definition shall appear in the global scope or in a namespace scope (3.3.6).5Because a namespace-definition contains declarations in its namespace-body and a namespace-definition isitself a declaration, it follows that namespace-definitions can be nested.

[ Example:namespace Outer {int i;namespace Inner {void f() { i++; }int i;void g() { i++; }}}// Outer::i// Inner::i§ 7.3.1© ISO/IEC 2011 – All rights reserved161ISO/IEC 14882:2011(E)— end example ]6The enclosing namespaces of a declaration are those namespaces in which the declaration lexically appears,except for a redeclaration of a namespace member outside its original namespace (e.g., a definition asspecified in 7.3.1.2). Such a redeclaration has the same enclosing namespaces as the original declaration.[ Example:namespace Q {namespace V {void f();// enclosing namespaces are the global namespace, Q, and Q::Vclass C { void m(); };}void V::f() { // enclosing namespaces are the global namespace, Q, and Q::Vextern void h(); // ... so this declares Q::V::h}void V::C::m() { // enclosing namespaces are the global namespace, Q, and Q::V}}— end example ]7If the optional initial inline keyword appears in a namespace-definition for a particular namespace, thatnamespace is declared to be an inline namespace.

The inline keyword may be used on an extensionnamespace-definition only if it was previously used on the original-namespace-definition for that namespace.8Members of an inline namespace can be used in most respects as though they were members of the enclosingnamespace. Specifically, the inline namespace and its enclosing namespace are both added to the set ofassociated namespaces used in argument-dependent lookup (3.4.2) whenever one of them is, and a usingdirective (7.3.4) that names the inline namespace is implicitly inserted into the enclosing namespace as foran unnamed namespace (7.3.1.1).

Furthermore, each member of the inline namespace can subsequently beexplicitly instantiated (14.7.2) or explicitly specialized (14.7.3) as though it were a member of the enclosingnamespace. Finally, looking up a name in the enclosing namespace via explicit qualification (3.4.3.2) willinclude members of the inline namespace brought in by the using-directive even if there are declarations ofthat name in the enclosing namespace.9These properties are transitive: if a namespace N contains an inline namespace M, which in turn contains aninline namespace O, then the members of O can be used as though they were members of M or N. The inlinenamespace set of N is the transitive closure of all inline namespaces in N.

The enclosing namespace set of Ois the set of namespaces consisting of the innermost non-inline namespace enclosing an inline namespace O,together with any intervening inline namespaces.7.3.1.11Unnamed namespaces[namespace.unnamed]An unnamed-namespace-definition behaves as if it were replaced byinlineopt namespace unique { /* empty body */ }using namespace unique ;namespace unique { namespace-body }where inline appears if and only if it appears in the unnamed-namespace-definition, all occurrences ofunique in a translation unit are replaced by the same identifier, and this identifier differs from all otheridentifiers in the entire program.94 [ Example:namespace { int i; }void f() { i++; }// unique ::i// unique ::i++94) Although entities in an unnamed namespace might have external linkage, they are effectively qualified by a name uniqueto their translation unit and therefore can never be seen from any other translation unit.§ 7.3.1.1162© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)namespace A {namespace {int i;int j;}void g() { i++; }}using namespace A;void h() {i++;A::i++;j++;}// A:: unique ::i// A:: unique ::j// A:: unique ::i++// error: unique ::i or A:: unique ::i// A:: unique ::i// A:: unique ::j— end example ]7.3.1.21Namespace member definitions[namespace.memdef ]Members (including explicit specializations of templates (14.7.3)) of a namespace can be defined within thatnamespace.

[ Example:namespace X {void f() { /∗ ... ∗/ }}— end example ]2Members of a named namespace can also be defined outside that namespace by explicit qualification (3.4.3.2)of the name being defined, provided that the entity being defined was already declared in the namespaceand the definition appears after the point of declaration in a namespace that encloses the declaration’snamespace. [ Example:namespace Q {namespace Vvoid f();}void V::f()void V::g()namespace Vvoid g();}}{{ /∗ ... ∗/ }{ /∗ ...

∗/ }{namespace R {void Q::V::g() { /∗ ... ∗/ }}// OK// error: g() is not yet a member of V// error: R doesn’t enclose Q— end example ]3Every name first declared in a namespace is a member of that namespace. If a friend declaration in a nonlocal class first declares a class or function95 the friend class or function is a member of the innermost enclosingnamespace. The name of the friend is not found by unqualified lookup (3.4.1) or by qualified lookup (3.4.3)95) this implies that the name of the class or function is unqualified.§ 7.3.1.2© ISO/IEC 2011 – All rights reserved163ISO/IEC 14882:2011(E)until a matching declaration is provided in that namespace scope (either before or after the class definitiongranting friendship).

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

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

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

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