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

Стандарт C++ 98 (1119566), страница 36

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

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

The identifier in an original-namespacedefinition is the name of the namespace. Subsequently in that declarative region, it is treated as anoriginal-namespace-name.3The original-namespace-name in an extension-namespace-definition shall have previously been defined inan original-namespace-definition in the same declarative region.4Every namespace-definition shall appear in the global scope or in a namespace scope (3.3.5).1125© ISO/IECISO/IEC 14882:1998(E)7 Declarations7.3.1 Namespace definitionBecause 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—end example]7.3.1.1 Unnamed namespaces1[namespace.unnamed]An unnamed-namespace-definition behaves as if it were replaced bynamespace unique { /* empty body */ }using namespace unique;namespace unique { namespace-body }where all occurrences of unique in a translation unit are replaced by the same identifier and this identifierdiffers from all other identifiers in the entire program.82) [Example:namespace { int i; }void f() { i++; }namespace A {namespace {int i;int j;}void g() { i++; }}using namespace A;void h() {i++;A::i++;j++;}// unique::i// unique::i++// A::unique::i// A::unique::j// A::unique::i++// error: unique::i or A::unique::i// A::unique::i// A::unique::j—end example]2The use of the static keyword is deprecated when declaring objects in a namespace scope (see annex D);the unnamed-namespace provides a superior alternative.7.3.1.2 Namespace member definitions1[namespace.memdef]Members of a namespace can be defined within that namespace.

[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 thenamespace and the definition appears after the point of declaration in a namespace that encloses the__________________82) Although entities in an unnamed namespace might have external linkage, they are effectively qualified by a name unique to theirtranslation unit and therefore can never be seen from any other translation unit.113ISO/IEC 14882:1998(E)© ISO/IEC7.3.1.2 Namespace member definitions7 Declarationsdeclaration’s namespace.

[Example:namespace Q {namespace V {void f();}void V::f() { /* ... */ }void V::g() { /* ... */ }namespace V {void g();}}// OK// error: g() is not yet a member of Vnamespace R {void Q::V::g() { /* ... */ }}// 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 anon-local class first declares a class or function83) the friend class or function is a member of the innermostenclosing namespace.

The name of the friend is not found by simple name lookup until a matching declaration is provided in that namespace scope (either before or after the class declaration granting friendship). Ifa friend function is called, its name may be found by the name lookup that considers functions from namespaces and classes associated with the types of the function arguments (3.4.2). When looking for a priordeclaration of a class or a function declared as a friend, scopes outside the innermost enclosing namespace scope are not considered. [Example:// Assume f and g have not yet been defined.void h(int);namespace A {class X {friend void f(X);// A::f is a friendclass Y {friend void g();// A::g is a friendfriend void h(int);// A::h is a friend// ::h not considered};};// A::f, A::g and A::h are not visible hereX x;void g() { f(x); }// definition of A::gvoid f(X) { /* ...

*/}// definition of A::fvoid h(int) { /* ... */ }// definition of A::h// A::f, A::g and A::h are visible here and known to be friends}using A::x;void h(){A::f(x);A::X::f(x);A::X::Y::g();}// error: f is not a member of A::X// error: g is not a member of A::X::Y—end example]__________________83) this implies that the name of the class or function is unqualified.114© ISO/IECISO/IEC 14882:1998(E)7 Declarations7.3.2 Namespace alias7.3.2 Namespace alias1[namespace.alias]A namespace-alias-definition declares an alternate name for a namespace according to the following grammar:namespace-alias:identifiernamespace-alias-definition:namespace identifier = qualified-namespace-specifier ;qualified-namespace-specifier:::opt nested-name-specifieropt namespace-name2The identifier in a namespace-alias-definition is a synonym for the name of the namespace denoted by thequalified-namespace-specifier and becomes a namespace-alias.

[Note: when looking up a namespacename in a namespace-alias-definition, only namespace names are considered, see 3.4.6. ]3In a declarative region, a namespace-alias-definition can be used to redefine a namespace-alias declared inthat declarative region to refer only to the namespace to which it already refers. [Example: the followingdeclarations are well-formed:namespacenamespacenamespacenamespaceCompany_with_very_long_name { /* ... */ }CWVLN = Company_with_very_long_name;CWVLN = Company_with_very_long_name;CWVLN = CWVLN;// OK: duplicate—end example]4A namespace-name or namespace-alias shall not be declared as the name of any other entity in the samedeclarative region. A namespace-name defined at global scope shall not be declared as the name of anyother entity in any global scope of the program. No diagnostic is required for a violation of this rule bydeclarations in different translation units.7.3.3 The using declaration1[namespace.udecl]A using-declaration introduces a name into the declarative region in which the using-declaration appears.That name is a synonym for the name of some entity declared elsewhere.using-declaration:using typenameopt ::opt nested-name-specifier unqualified-id ;using :: unqualified-id ;2The member name specified in a using-declaration is declared in the declarative region in which the usingdeclaration appears.

[Note: only the specified name is so declared; specifying an enumeration name in ausing-declaration does not declare its enumerators in the using-declaration’s declarative region. ]3Every using-declaration is a declaration and a member-declaration and so can be used in a class definition.[Example:struct B {void f(char);void g(char);enum E { e };union { int x; };};struct D : B {using B::f;void f(int) { f(’c’); }void g(int) { g(’c’); }};// calls B::f(char)// recursively calls D::g(int)115ISO/IEC 14882:1998(E)© ISO/IEC7.3.3 The using declaration7 Declarations—end example]4A using-declaration used as a member-declaration shall refer to a member of a base class of the class beingdefined, shall refer to a member of an anonymous union that is a member of a base class of the class beingdefined, or shall refer to an enumerator for an enumeration type that is a member of a base class of the classbeing defined.

[Example:class C {int g();};class D2 : public B {using B::f;using B::e;using B::x;using C::g;};// OK: B is a base of D2// OK: e is an enumerator of base B// OK: x is a union member of base B// error: C isn’t a base of D2—end example] [Note: since constructors and destructors do not have names, a using-declaration cannotrefer to a constructor or a destructor for a base class. Since specializations of member templates for conversion functions are not found by name lookup, they are not considered when a using-declaration specifies aconversion function (14.5.2). ] If an assignment operator brought from a base class into a derived classscope has the signature of a copy-assignment operator for the derived class (12.8), the using-declarationdoes not by itself suppress the implicit declaration of the derived class copy-assignment operator; thecopy-assignment operator from the base class is hidden or overridden by the implicitly-declared copyassignment operator of the derived class, as described below.5A using-declaration shall not name a template-id.

[Example:class A {public:template <class T> void f(T);template <class T> struct X { };};class B : public A {public:using A::f<double>;// ill-formedusing A::X<int>;// ill-formed};—end example]6A using-declaration for a class member shall be a member-declaration. [Example:struct X {int i;static int s;};void f(){using X::i;using X::s;// error: X::i is a class member// and this is not a member declaration.// error: X::s is a class member// and this is not a member declaration.}—end example]7Members declared by a using-declaration can be referred to by explicit qualification just like other membernames (3.4.3.2). In a using-declaration, a prefix :: refers to the global namespace.

[Example:116© ISO/IECISO/IEC 14882:1998(E)7 Declarations7.3.3 The using declarationvoid f();namespace A {void g();}namespace X {using ::f;using A::g;}void h(){X::f();X::g();}// global f// A’s g// calls ::f// calls A::g—end example]8A using-declaration is a declaration and can therefore be used repeatedly where (and only where) multipledeclarations are allowed.

[Example:namespace A {int i;}namespace A1 {using A::i;using A::i;}void f(){using A::i;using A::i;}// OK: double declaration// error: double declarationclass B {public:int i;};class X : public B {using B::i;using B::i;};// error: double member declaration—end example]9The entity declared by a using-declaration shall be known in the context using it according to its definitionat the point of the using-declaration. Definitions added to the namespace after the using-declaration arenot considered when a use of the name is made. [Example:namespace A {void f(int);}using A::f;// f is a synonym for A::f;// that is, for A::f(int).namespace A {void f(char);}117ISO/IEC 14882:1998(E)© ISO/IEC7.3.3 The using declarationvoid foo(){f(’a’);}void bar(){using A::f;f(’a’);7 Declarations// calls f(int),// even though f(char) exists.// f is a synonym for A::f;// that is, for A::f(int) and A::f(char).// calls f(char)}—end example] [Note: partial specializations of class templates are found by looking up the primary classtemplate and then considering all partial specializations of that template.

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

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

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

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