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

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

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

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

[ Example:namespace A {namespace B {void f1(int);}using namespace B;}void A::f1(int){ } // ill-formed, f1 is not a member of A— end example ] However, in such namespace member declarations, the nested-name-specifier may rely onusing-directives to implicitly provide the initial part of the nested-name-specifier. [ Example:namespace A {namespace B {void f1(int);}}namespace C {namespace D {void f1(int);}}using namespace A;using namespace C::D;void B::f1(int){ } // OK, defines A::B::f1(int)— end example ]3.4.4Elaborated type specifiers[basic.lookup.elab]1An elaborated-type-specifier (7.1.6.3) may be used to refer to a previously declared class-name or enum-nameeven though the name has been hidden by a non-type declaration (3.3.10).2If the elaborated-type-specifier has no nested-name-specifier, and unless the elaborated-type-specifier appearsin a declaration with the following form:class-key attribute-specifier-seqopt identifier ;§ 3.4.456© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)the identifier is looked up according to 3.4.1 but ignoring any non-type names that have been declared.

Ifthe elaborated-type-specifier is introduced by the enum keyword and this lookup does not find a previouslydeclared type-name, the elaborated-type-specifier is ill-formed. If the elaborated-type-specifier is introduced bythe class-key and this lookup does not find a previously declared type-name, or if the elaborated-type-specifierappears in a declaration with the form:class-key attribute-specifier-seqopt identifier ;the elaborated-type-specifier is a declaration that introduces the class-name as described in 3.3.2.3If the elaborated-type-specifier has a nested-name-specifier, qualified name lookup is performed, as describedin 3.4.3, but ignoring any non-type names that have been declared.

If the name lookup does not find apreviously declared type-name, the elaborated-type-specifier is ill-formed. [ Example:struct Node {struct Node* Next;struct Data* Data;// OK: Refers to Node at global scope// OK: Declares type Data// at global scope and member Data};struct Data {struct Node* Node;friend struct ::Glob;////////OK: Refers to Node at global scopeerror: Glob is not declaredcannot introduce a qualified type (7.1.6.3)OK: Refers to (as yet) undeclared Globstruct Base {struct Data;struct ::Data*thatData;struct Base::Data* thisData;friend class ::Data;friend class Data;struct Data { /* ... */ };};////////////OK: Declares nested DataOK: Refers to ::DataOK: Refers to nested DataOK: global Data is a friendOK: nested Data is a friendDefines nested Datastructstructstructstructstruct//////////OK: Redeclares Data at global scopeerror: cannot introduce a qualified type (7.1.6.3)error: cannot introduce a qualified type (7.1.6.3)error: Datum undefinedOK: refers to nested Datafriend struct Glob;// at global scope./∗ ...

∗/};Data;::Data;Base::Data;Base::Datum;Base::Data* pBase;— end example ]3.4.5Class member access[basic.lookup.classref ]1In a class member access expression (5.2.5), if the . or -> token is immediately followed by an identifierfollowed by a <, the identifier must be looked up to determine whether the < is the beginning of a templateargument list (14.2) or a less-than operator. The identifier is first looked up in the class of the objectexpression. If the identifier is not found, it is then looked up in the context of the entire postfix-expressionand shall name a class template.2If the id-expression in a class member access (5.2.5) is an unqualified-id, and the type of the object expressionis of a class type C, the unqualified-id is looked up in the scope of class C.

For a pseudo-destructor call (5.2.4),§ 3.4.5© ISO/IEC 2011 – All rights reserved57ISO/IEC 14882:2011(E)the unqualified-id is looked up in the context of the complete postfix-expression.3If the unqualified-id is ~type-name, the type-name is looked up in the context of the entire postfix-expression.If the type T of the object expression is of a class type C, the type-name is also looked up in the scope ofclass C. At least one of the lookups shall find a name that refers to (possibly cv-qualified) T. [ Example:struct A { };struct B {struct A { };void f(::A* a);};void B::f(::A* a) {a->~A();}// OK: lookup in *a finds the injected-class-name— end example ]4If the id-expression in a class member access is a qualified-id of the formclass-name-or-namespace-name::...the class-name-or-namespace-name following the . or -> operator is first looked up in the class of theobject expression and the name, if found, is used.

Otherwise it is looked up in the context of the entirepostfix-expression. [ Note: See 3.4.3, which describes the lookup of a name before ::, which will only find atype or namespace name. — end note ]5If the qualified-id has the form::class-name-or-namespace-name::...the class-name-or-namespace-name is looked up in global scope as a class-name or namespace-name.6If the nested-name-specifier contains a simple-template-id (14.2), the names in its template-arguments arelooked up in the context in which the entire postfix-expression occurs.7If the id-expression is a conversion-function-id, its conversion-type-id is first looked up in the class of theobject expression and the name, if found, is used.

Otherwise it is looked up in the context of the entirepostfix-expression. In each of these lookups, only names that denote types or templates whose specializationsare types are considered. [ Example:struct A { };namespace N {struct A {void g() { }template <class T> operator T();};}int main() {N::A a;a.operator A();}// calls N::A::operator N::A— end example ]§ 3.4.558© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)3.4.61[basic.lookup.udir]In a using-directive or namespace-alias-definition, during the lookup for a namespace-name or for a name ina nested-name-specifier only namespace names are considered.3.51Using-directives and namespace aliasesProgram and linkage[basic.link]A program consists of one or more translation units (Clause 2) linked together.

A translation unit consistsof a sequence of declarations.translation-unit:declaration-seqopt2A name is said to have linkage when it might denote the same object, reference, function, type, template,namespace or value as a name introduced by a declaration in another scope:— When a name has external linkage , the entity it denotes can be referred to by names from scopes ofother translation units or from other scopes of the same translation unit.— When a name has internal linkage , the entity it denotes can be referred to by names from other scopesin the same translation unit.— When a name has no linkage , the entity it denotes cannot be referred to by names from other scopes.3A name having namespace scope (3.3.6) has internal linkage if it is the name of— a variable, function or function template that is explicitly declared static; or,— a variable that is explicitly declared const or constexpr and neither explicitly declared extern norpreviously declared to have external linkage; or— a data member of an anonymous union.4An unnamed namespace or a namespace declared directly or indirectly within an unnamed namespace hasinternal linkage.

All other namespaces have external linkage. A name having namespace scope that has notbeen given internal linkage above has the same linkage as the enclosing namespace if it is the name of— a variable; or— a function; or— a named class (Clause 9), or an unnamed class defined in a typedef declaration in which the class hasthe typedef name for linkage purposes (7.1.3); or— a named enumeration (7.2), or an unnamed enumeration defined in a typedef declaration in which theenumeration has the typedef name for linkage purposes (7.1.3); or— an enumerator belonging to an enumeration with linkage; or— a template.5In addition, a member function, static data member, a named class or enumeration of class scope, or anunnamed class or enumeration defined in a class-scope typedef declaration such that the class or enumerationhas the typedef name for linkage purposes (7.1.3), has external linkage if the name of the class has externallinkage.6The name of a function declared in block scope and the name of a variable declared by a block scope externdeclaration have linkage.

If there is a visible declaration of an entity with linkage having the same name andtype, ignoring entities declared outside the innermost enclosing namespace scope, the block scope declarationdeclares that same entity and receives the linkage of the previous declaration. If there is more than one such§ 3.5© ISO/IEC 2011 – All rights reserved59ISO/IEC 14882:2011(E)matching entity, the program is ill-formed.

Otherwise, if no matching entity is found, the block scope entityreceives external linkage.[ Example:static void f();static int i = 0;void g() {extern void f();int i;{extern void f();extern int i;}}// #1// internal linkage// #2 i has no linkage// internal linkage// #3 external linkageThere are three objects named i in this program. The object with internal linkage introduced by thedeclaration in global scope (line #1 ), the object with automatic storage duration and no linkage introducedby the declaration on line #2, and the object with static storage duration and external linkage introducedby the declaration on line #3.

— end example ]7When a block scope declaration of an entity with linkage is not found to refer to some other declaration,then that entity is a member of the innermost enclosing namespace. However such a declaration does notintroduce the member name in its namespace scope. [ Example:namespace X {void p() {q();extern void q();}// error: q not yet declared// q is a member of namespace Xvoid middle() {q();}void q() { /* ...// error: q not yet declared*/ }// definition of X::q}void q() { /* ...*/ }// some other, unrelated q— end example ]8Names not covered by these rules have no linkage. Moreover, except as noted, a name declared at blockscope (3.3.3) has no linkage. A type is said to have linkage if and only if:— it is a class or enumeration type that is named (or has a name for linkage purposes (7.1.3)) and thename has linkage; or— it is an unnamed class or enumeration member of a class with linkage; or— it is a specialization of a class template (14)33 ; or— it is a fundamental type (3.9.1); or— it is a compound type (3.9.2) other than a class or enumeration, compounded exclusively from typesthat have linkage; or33) A class template always has external linkage, and the requirements of 14.3.1 and 14.3.2 ensure that the template argumentswill also have appropriate linkage.§ 3.560© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)— it is a cv-qualified (3.9.3) version of a type that has linkage.A type without linkage shall not be used as the type of a variable or function with external linkage unless— the entity has C language linkage (7.5), or— the entity is declared within an unnamed namespace (7.3.1), or— the entity is not odr-used (3.2) or is defined in the same translation unit.[ Note: In other words, a type without linkage contains a class or enumeration that cannot be named outsideits translation unit.

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

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

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

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