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

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

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

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

No diagnostic is required for a violation of this rule.3) If reordering member declarations in a class yields an alternate valid program under (1) and (2), theprogram is ill-formed, no diagnostic is required.4) A name declared within a member function hides a declaration of the same name whose scope extendsto or past the end of the member function’s class.5) The potential scope of a declaration that extends to or past the end of a class definition also extends to the regions defined by its member definitions, even if the members are defined lexicallyoutside the class (this includes static data member definitions, nested class definitions, member function definitions (including the member function body and any portion of the declarator part of suchdefinitions which follows the declarator-id, including a parameter-declaration-clause and any defaultarguments (8.3.6).[ Example:§ 3.3.742© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)typedef int c;enum { i = 1 };class X {char v[i];int f() { return sizeof(c); }char c;enum { i = 2 };// error: i refers to ::i// but when reevaluated is X::i// OK: X::c};typedef char*struct Y {T a;typedef longT b;T;// error: T refers to ::T// but when reevaluated is Y::TT;};typedef int I;class D {typedef I I;};// error, even though no reordering involved— end example ]2The name of a class member shall only be used as follows:— in the scope of its class (as described above) or a class derived (Clause 10) from its class,— after the .

operator applied to an expression of the type of its class (5.2.5) or a class derived from itsclass,— after the -> operator applied to a pointer to an object of its class (5.2.5) or a class derived from itsclass,— after the :: scope resolution operator (5.1) applied to the name of its class or a class derived from itsclass.3.3.81Enumeration scope[basic.scope.enum]The name of a scoped enumerator (7.2) has enumeration scope.

Its potential scope begins at its point ofdeclaration and terminates at the end of the enum-specifier.3.3.9Template parameter scope[basic.scope.temp]1The declarative region of the name of a template parameter of a template template-parameter is the smallesttemplate-parameter-list in which the name was introduced.2The declarative region of the name of a template parameter of a template is the smallest template-declarationin which the name was introduced. Only template parameter names belong to this declarative region; anyother kind of name introduced by the declaration of a template-declaration is instead introduced into thesame declarative region where it would be introduced as a result of a non-template declaration of the samename.

[ Example:namespace N {template<class T> struct A { };// #1§ 3.3.9© ISO/IEC 2011 – All rights reserved43ISO/IEC 14882:2011(E)template<class U> void f(U) { }struct B {template<class V> friend int g(struct C*);};// #2// #3}The declarative regions of T, U and V are the template-declarations on lines #1, #2 and #3, respectively.But the names A, f, g and C all belong to the same declarative region — namely, the namespace-body of N.(g is still considered to belong to this declarative region in spite of its being hidden during qualified andunqualified name lookup.) — end example ]3The potential scope of a template parameter name begins at its point of declaration (3.3.2) and ends at theend of its declarative region.

[ Note: This implies that a template-parameter can be used in the declarationof subsequent template-parameters and their default arguments but cannot be used in preceding templateparameters or their default arguments. For example,template<class T, T* p, class U = T> class X { /∗ ... ∗/ };template<class T> void f(T* p = new T);This also implies that a template-parameter can be used in the specification of base classes. For example,template<class T> class X : public Array<T> { /∗ ... ∗/ };template<class T> class Y : public T { /∗ ... ∗/ };The use of a template parameter as a base class implies that a class used as a template argument must bedefined and not just declared when the class template is instantiated. — end note ]4The declarative region of the name of a template parameter is nested within the immediately-enclosingdeclarative region.

[ Note: As a result, a template-parameter hides any entity with the same name in anenclosing scope (3.3.10). [ Example:typedef int N;template<N X, typename N, template<N Y> class T> struct A;Here, X is a non-type template parameter of type int and Y is a non-type template parameter of the sametype as the second template parameter of A. — end example ] — end note ]5[ Note: Because the name of a template parameter cannot be redeclared within its potential scope (14.6.1), atemplate parameter’s scope is often its potential scope.

However, it is still possible for a template parametername to be hidden; see 14.6.1. — end note ]3.3.10Name hiding[basic.scope.hiding]1A name can be hidden by an explicit declaration of that same name in a nested declarative region or derivedclass (10.2).2A class name (9.1) or enumeration name (7.2) can be hidden by the name of a variable, data member,function, or enumerator declared in the same scope. If a class or enumeration name and a variable, datamember, function, or enumerator are declared in the same scope (in any order) with the same name, theclass or enumeration name is hidden wherever the variable, data member, function, or enumerator name isvisible.3In a member function definition, the declaration of a name at block scope hides the declaration of a memberof the class with the same name; see 3.3.7.

The declaration of a member in a derived class (Clause 10) hidesthe declaration of a member of a base class of the same name; see 10.2.§ 3.3.1044© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)4During the lookup of a name qualified by a namespace name, declarations that would otherwise be madevisible by a using-directive can be hidden by declarations with the same name in the namespace containingthe using-directive; see (3.4.3.2).5If a name is in scope and is not hidden it is said to be visible.3.4Name lookup[basic.lookup]1The name lookup rules apply uniformly to all names (including typedef-names (7.1.3), namespace-names (7.3),and class-names (9.1)) wherever the grammar allows such names in the context discussed by a particularrule.

Name lookup associates the use of a name with a declaration (3.1) of that name. Name lookup shallfind an unambiguous declaration for the name (see 10.2). Name lookup may associate more than one declaration with a name if it finds the name to be a function name; the declarations are said to form a setof overloaded functions (13.1). Overload resolution (13.3) takes place after name lookup has succeeded.The access rules (Clause 11) are considered only once name lookup and function overload resolution (ifapplicable) have succeeded. Only after name lookup, function overload resolution (if applicable) and accesschecking have succeeded are the attributes introduced by the name’s declaration used further in expressionprocessing (Clause 5).2A name “looked up in the context of an expression” is looked up as an unqualified name in the scope wherethe expression is found.3The injected-class-name of a class (Clause 9) is also considered to be a member of that class for the purposesof name hiding and lookup.4[ Note: 3.5 discusses linkage issues.

The notions of scope, point of declaration and name hiding are discussedin 3.3. — end note ]3.4.1Unqualified name lookup[basic.lookup.unqual]1In all the cases listed in 3.4.1, the scopes are searched for a declaration in the order listed in each of therespective categories; name lookup ends as soon as a declaration is found for the name. If no declaration isfound, the program is ill-formed.2The declarations from the namespace nominated by a using-directive become visible in a namespace enclosingthe using-directive; see 7.3.4.

For the purpose of the unqualified name lookup rules described in 3.4.1, thedeclarations from the namespace nominated by the using-directive are considered members of that enclosingnamespace.3The lookup for an unqualified name used as the postfix-expression of a function call is described in 3.4.2.[ Note: For purposes of determining (during parsing) whether an expression is a postfix-expression for a function call, the usual name lookup rules apply. The rules in 3.4.2 have no effect on the syntactic interpretationof an expression. For example,typedef int f;namespace N {struct A {friend void f(A &);operator int();void g(A a) {int i = f(a);// f is the typedef, not the friend// function: equivalent to int(a)}};}§ 3.4.1© ISO/IEC 2011 – All rights reserved45ISO/IEC 14882:2011(E)Because the expression is not a function call, the argument-dependent name lookup (3.4.2) does not applyand the friend function f is not found.

— end note ]4A name used in global scope, outside of any function, class or user-declared namespace, shall be declaredbefore its use in global scope.5A name used in a user-declared namespace outside of the definition of any function or class shall be declaredbefore its use in that namespace or before its use in a namespace enclosing its namespace.6A name used in the definition of a function following the function’s declarator-id 28 that is a member ofnamespace N (where, only for the purpose of exposition, N could represent the global scope) shall be declaredbefore its use in the block in which it is used or in one of its enclosing blocks (6.3) or, shall be declaredbefore its use in namespace N or, if N is a nested namespace, shall be declared before its use in one of N’senclosing namespaces. [ Example:namespace A {namespace N {void f();}}void A::N::f() {i = 5;// The following scopes are searched for a declaration of i:// 1) outermost block scope of A::N::f, before the use of i// 2) scope of namespace N// 3) scope of namespace A// 4) global scope, before the definition of A::N::f}— end example ]7A name used in the definition of a class X outside of a member function body or nested class definition29shall be declared in one of the following ways:— before its use in class X or be a member of a base class of X (10.2), or— if X is a nested class of class Y (9.7), before the definition of X in Y, or shall be a member of a baseclass of Y (this lookup applies in turn to Y ’s enclosing classes, starting with the innermost enclosingclass),30 or— if X is a local class (9.8) or is a nested class of a local class, before the definition of class X in a blockenclosing the definition of class X, or— if X is a member of namespace N, or is a nested class of a class that is a member of N, or is a local classor a nested class within a local class of a function that is a member of N, before the definition of classX in namespace N or in one of N ’s enclosing namespaces.[ Example:namespace M {class B { };}28) This refers to unqualified names that occur, for instance, in a type or default argument in the parameter-declaration-clauseor used in the function body.29) This refers to unqualified names following the class name; such a name may be used in the base-clause or may be used inthe class definition.30) This lookup applies whether the definition of X is nested within Y’s definition or whether X’s definition appears in anamespace scope enclosing Y ’s definition (9.7).§ 3.4.146© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)namespaceclass Yclassint};};}////////////N {: public M::B {X {a[i];The following scopes are searched for a declaration of i:1) scope of class N::Y::X, before the use of i2) scope of class N::Y, before the definition of N::Y::X3) scope of N::Y’s base class M::B4) scope of namespace N, before the definition of N::Y5) global scope, before the definition of N— end example ] [ Note: When looking for a prior declaration of a class or function introduced by a frienddeclaration, scopes outside of the innermost enclosing namespace scope are not considered; see 7.3.1.2.

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

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

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

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