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

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

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

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

If a using-declaration names aclass template, partial specializations introduced after the using-declaration are effectively visible becausethe primary template is visible (14.5.4). ]10Since a using-declaration is a declaration, the restrictions on declarations of the same name in the samedeclarative region (3.3) also apply to using-declarations. [Example:namespace A {int x;}namespace B {int i;struct g { };struct x { };void f(int);void f(double);void g(char);}void func(){int i;using B::i;void f(char);using B::f;f(3.5);using B::g;g(’a’);struct g g1;using B::x;using A::x;x = 99;struct x x1;}// OK: hides struct g// error: i declared twice// OK: each f is a function// calls B::f(double)// calls B::g(char)// g1 has class type B::g// OK: hides struct B::x// assigns to A::x// x1 has class type B::x—end example]11If a function declaration in namespace scope or block scope has the same name and the same parametertypes as a function introduced by a using-declaration, the program is ill-formed.

[Note: two usingdeclarations may introduce functions with the same name and the same parameter types. If, for a call to anunqualified function name, function overload resolution selects the functions introduced by such usingdeclarations, the function call is ill-formed.118© ISO/IECISO/IEC 14882:1998(E)7 Declarations7.3.3 The using declaration[Example:namespace B {void f(int);void f(double);}namespace C {void f(int);void f(double);void f(char);}void h(){using B::f;using C::f;f(’h’);f(1);void f(int);// B::f(int) and B::f(double)// C::f(int), C::f(double), and C::f(char)// calls C::f(char)// error: ambiguous: B::f(int) or C::f(int) ?// error:// f(int) conflicts with C::f(int) and B::f(int)}—end example] ]12When a using-declaration brings names from a base class into a derived class scope, member functions inthe derived class override and/or hide member functions with the same name and parameter types in a baseclass (rather than conflicting).

[Example:struct B {virtual void f(int);virtual void f(char);void g(int);void h(int);};struct D : B {using B::f;void f(int);// OK: D::f(int) overrides B::f(int);using B::g;void g(char);// OKusing B::h;void h(int);// OK: D::h(int) hides B::h(int)};void k(D* p){p->f(1);p->f(’a’);p->g(1);p->g(’a’);}// calls D::f(int)// calls B::f(char)// calls B::g(int)// calls D::g(char)—end example] [Note: two using-declarations may introduce functions with the same name and the sameparameter types.

If, for a call to an unqualified function name, function overload resolution selects thefunctions introduced by such using-declarations, the function call is ill-formed. ]13For the purpose of overload resolution, the functions which are introduced by a using-declaration into aderived class will be treated as though they were members of the derived class.

In particular, the implicitthis parameter shall be treated as if it were a pointer to the derived class rather than to the base class.This has no effect on the type of the function, and in all other respects the function remains a member of thebase class.119ISO/IEC 14882:1998(E)© ISO/IEC7.3.3 The using declaration147 DeclarationsAll instances of the name mentioned in a using-declaration shall be accessible. In particular, if a derivedclass uses a using-declaration to access a member of a base class, the member name shall be accessible. Ifthe name is that of an overloaded member function, then all functions named shall be accessible. The baseclass members mentioned by a using-declaration shall be visible in the scope of at least one of the directbase classes of the class where the using-declaration is specified.

[Note: because a using-declaration designates a base class member (and not a member subobject or a member function of a base class subobject),a using-declaration cannot be used to resolve inherited member ambiguities. For example,struct A { int x(); };struct B : A { };struct C : A {using A::x;int x(int);};struct D : B, C {using C::x;int x(double);};int f(D* d) {return d->x();}// ambiguous: B::x or C::x]15The alias created by the using-declaration has the usual accessibility for a member-declaration. [Example:class A {private:void f(char);public:void f(int);protected:void g();};class B : public A {using A::f;public:using A::g;};// error: A::f(char) is inaccessible// B::g is a public synonym for A::g—end example]16[Note: use of access-declarations (11.3) is deprecated; member using-declarations provide a better alternative.

]7.3.4 Using directiveusing-directive:using[namespace.udir]namespace ::opt nested-name-specifieropt namespace-name ;A using-directive shall not appear in class scope, but may appear in namespace scope or in block scope.[Note: when looking up a namespace-name in a using-directive, only namespace names are considered, see3.4.6.

]1A using-directive specifies that the names in the nominated namespace can be used in the scope in whichthe using-directive appears after the using-directive. During unqualified name lookup (3.4.1), the namesappear as if they were declared in the nearest enclosing namespace which contains both the using-directiveand the nominated namespace. [Note: in this context, “contains” means “contains directly or indirectly”. ]120© ISO/IECISO/IEC 14882:1998(E)7 Declarations7.3.4 Using directiveA using-directive does not add any members to the declarative region in which it appears. [Example:namespace A {int i;namespace B {namespace C {int i;}using namespacevoid f1() {i = 5;}}namespace D {using namespaceusing namespacevoid f2() {i = 5;}}void f3() {i = 5;}}void f4() {i = 5;}A::B::C;// OK, C::i visible in B and hides A::iB;C;// ambiguous, B::C::i or A::i?// uses A::i// ill-formed; neither i is visible]2The using-directive is transitive: if a scope contains a using-directive that nominates a second namespacethat itself contains using-directives, the effect is as if the using-directives from the second namespace alsoappeared in the first.

[Example:namespace M {int i;}namespace N {int i;using namespace M;}void f(){using namespace N;i = 7;}// error: both M::i and N::i are visible121ISO/IEC 14882:1998(E)© ISO/IEC7.3.4 Using directive7 DeclarationsFor another example,namespace A {int i;}namespace B {int i;int j;namespace C {namespace D {using namespace A;int j;int k;int a = i;// B::i hides A::i}using namespace D;int k = 89;// no problem yetint l = k;// ambiguous: C::k or D::kint m = i;// B::i hides A::iint n = j;// D::j hides B::j}}—end example]3If a namespace is extended by an extended-namespace-definition after a using-directive for that namespaceis given, the additional members of the extended namespace and the members of namespaces nominated byusing-directives in the extended-namespace-definition can be used after the extended-namespace-definition.4If name lookup finds a declaration for a name in two different namespaces, and the declarations do notdeclare the same entity and do not declare functions, the use of the name is ill-formed.

[Note: in particular,the name of an object, function or enumerator does not hide the name of a class or enumeration declared ina different namespace. For example,namespace A {class X { };extern "C"extern "C++"}namespace B {void X(int);extern "C"extern "C++"}using namespace A;using namespace B;void f() {X(1);g();h();}int g();int h();int g();int h();// error: name X found in two namespaces// okay: name g refers to the same entity// error: name h found in two namespaces—end note]5During overload resolution, all functions from the transitive search are considered for argument matching.The set of declarations found by the transitive search is unordered.

[Note: in particular, the order in whichnamespaces were considered and the relationships among the namespaces implied by the using-directivesdo not cause preference to be given to any of the declarations found by the search. ] An ambiguity exists ifthe best match finds two functions with the same signature, even if one is in a namespace reachable throughusing-directives in the namespace of the other.84)__________________84) During name lookup in a class hierarchy, some ambiguities may be resolved by considering whether one member hides the other122© ISO/IECISO/IEC 14882:1998(E)7 Declarations7.3.4 Using directive[Example:namespace D {int d1;void f(char);}using namespace D;int d1;// OK: no conflict with D::d1namespace E {int e;void f(int);}namespace D {int d2;using namespace E;void f(int);}void f(){d1++;::d1++;D::d1++;d2++;e++;f(1);f(’a’);}// namespace extension// error: ambiguous ::d1 or D::d1?// OK// OK// OK: D::d2// OK: E::e// error: ambiguous: D::f(int) or E::f(int)?// OK: D::f(char)—end example]7.4 The asm declaration1[dcl.asm]An asm declaration has the formasm-definition:asm ( string-literal ) ;The meaning of an asm declaration is implementation-defined.

[Note: Typically it is used to pass information through the implementation to an assembler. ]7.5 Linkage specifications[dcl.link]1All function types, function names, and variable names have a language linkage. [Note: Some of the properties associated with an entity with language linkage are specific to each implementation and are notdescribed here. For example, a particular language linkage may be associated with a particular form of representing names of objects and functions with external linkage, or with a particular calling convention, etc.] The default language linkage of all function types, function names, and variable names is C++ languagelinkage. Two function types with different language linkages are distinct types even if they are otherwiseidentical.2Linkage (3.5) between C++ and non-C++ code fragments can be achieved using a linkage-specification:__________________along some paths (10.2).

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

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

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

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