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

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

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

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

[Example: consider the following:voidvoidvoidvoidffff(int i, int j);(int i, int j = 99);(int i = 88, int j);();void prog (){f (1, 2);f (1);f ();}// OK: redeclaration of f(int, int)// OK: redeclaration of f(int, int)// OK: overloaded declaration of f// OK: call f(int, int)// OK: call f(int, int)// Error: f(int, int) or f()?—end example] —end note]13.2 Declaration matching1[over.dcl]Two function declarations of the same name refer to the same function if they are in the same scope andhave equivalent parameter declarations (13.1). A function member of a derived class is not in the samescope as a function member of the same name in a base class.

[Example:class B {public:int f(int);};class D : public B {public:int f(char*);};Here D::f(char*) hides B::f(int) rather than overloading it.void h(D* pd){pd->f(1);pd->B::f(1);pd->f("Ben");// error:// D::f(char*) hides B::f(int)// OK// OK, calls D::f}—end example]2A locally declared function is not in the same scope as a function in a containing scope.

[Example:int f(char*);void g(){extern f(int);f("asdf");// error: f(int) hides f(char*)// so there is no f(char*) in this scope}211ISO/IEC 14882:1998(E)© ISO/IEC13.2 Declaration matching13 Overloadingvoid caller (){extern void callee(int, int);{extern void callee(int);callee(88, 99);}}// hides callee(int, int)// error: only callee(int) in scope—end example]3Different versions of an overloaded member function can be given different access rules. [Example:class buffer {private:char* p;int size;protected:buffer(int s, char* store) { size = s; p = store; }// ...public:buffer(int s) { p = new char[size = s]; }// ...};—end example]13.3 Overload resolution[over.match]1Overload resolution is a mechanism for selecting the best function to call given a list of expressions that areto be the arguments of the call and a set of candidate functions that can be called based on the context of thecall.

The selection criteria for the best function are the number of arguments, how well the argumentsmatch the types of the parameters of the candidate function, how well (for nonstatic member functions) theobject matches the implied object parameter, and certain other properties of the candidate function. [Note:the function selected by overload resolution is not guaranteed to be appropriate for the context. Otherrestrictions, such as the accessibility of the function, can make its use in the calling context ill-formed.

]2Overload resolution selects the function to call in seven distinct contexts within the language:— invocation of a function named in the function call syntax (13.3.1.1.1);— invocation of a function call operator, a pointer-to-function conversion function, a reference-to-pointerto-function conversion function, or a reference-to-function conversion function on a class object namedin the function call syntax (13.3.1.1.2);— invocation of the operator referenced in an expression (13.3.1.2);— invocation of a constructor for direct-initialization (8.5) of a class object (13.3.1.3);— invocation of a user-defined conversion for copy-initialization (8.5) of a class object (13.3.1.4);— invocation of a conversion function for initialization of an object of a nonclass type from an expressionof class type (13.3.1.5); and— invocation of a conversion function for conversion to an lvalue to which a reference (8.5.3) will bedirectly bound (13.3.1.6).3Each of these contexts defines the set of candidate functions and the list of arguments in its own uniqueway.

But, once the candidate functions and argument lists have been identified, the selection of the bestfunction is the same in all cases:— First, a subset of the candidate functions—those that have the proper number of arguments and meet212© ISO/IECISO/IEC 14882:1998(E)13 Overloading13.3 Overload resolutioncertain other conditions—is selected to form a set of viable functions (13.3.2).— Then the best viable function is selected based on the implicit conversion sequences (13.3.3.1) neededto match each argument to the corresponding parameter of each viable function.4If a best viable function exists and is unique, overload resolution succeeds and produces it as the result.Otherwise overload resolution fails and the invocation is ill-formed.

When overload resolution succeeds,and the best viable function is not accessible (clause 11) in the context in which it is used, the program isill-formed.13.3.1 Candidate functions and argument lists[over.match.funcs]1The subclauses of 13.3.1 describe the set of candidate functions and the argument list submitted to overloadresolution in each of the seven contexts in which overload resolution is used.

The source transformationsand constructions defined in these subclauses are only for the purpose of describing the overload resolutionprocess. An implementation is not required to use such transformations and constructions.2The set of candidate functions can contain both member and non-member functions to be resolved againstthe same argument list.

So that argument and parameter lists are comparable within this heterogeneous set,a member function is considered to have an extra parameter, called the implicit object parameter, whichrepresents the object for which the member function has been called. For the purposes of overload resolution, both static and non-static member functions have an implicit object parameter, but constructors do not.3Similarly, when appropriate, the context can construct an argument list that contains an implied objectargument to denote the object to be operated on. Since arguments and parameters are associated by position within their respective lists, the convention is that the implicit object parameter, if present, is alwaysthe first parameter and the implied object argument, if present, is always the first argument.4For non-static member functions, the type of the implicit object parameter is “reference to cv X” where X isthe class of which the function is a member and cv is the cv-qualification on the member function declaration.

[Example: for a const member function of class X, the extra parameter is assumed to have type “reference to const X”. ] For conversion functions, the function is considered to be a member of the class ofthe implicit object argument for the purpose of defining the type of the implicit object parameter. For nonconversion functions introduced by a using-declaration into a derived class, the function is considered to bea member of the derived class for the purpose of defining the type of the implicit object parameter. Forstatic member functions, the implicit object parameter is considered to match any object (since if the function is selected, the object is discarded). [Note: no actual type is established for the implicit object parameter of a static member function, and no attempt will be made to determine a conversion sequence for thatparameter (13.3.3).

]5During overload resolution, the implied object argument is indistinguishable from other arguments. Theimplicit object parameter, however, retains its identity since conversions on the corresponding argumentshall obey these additional rules:— no temporary object can be introduced to hold the argument for the implicit object parameter;— no user-defined conversions can be applied to achieve a type match with it; and— even if the implicit object parameter is not const-qualified, an rvalue temporary can be bound to theparameter as long as in all other respects the temporary can be converted to the type of the implicitobject parameter.6Because only one user-defined conversion is allowed in an implicit conversion sequence, special rulesapply when selecting the best user-defined conversion (13.3.3, 13.3.3.1).

[Example:class T {public:T();// ...};213ISO/IEC 14882:1998(E)© ISO/IEC13.3.1 Candidate functions and argument listsclass C : T {public:C(int);// ...};T a = 1;13 Overloading// ill-formed: T(C(1)) not tried—end example]7In each case where a candidate is a function template, candidate template functions are generated usingtemplate argument deduction (14.8.3, 14.8.2). Those candidates are then handled as candidate functions inthe usual way.113) A given name can refer to one or more function templates and also to a set of overloadednon-template functions. In such a case, the candidate functions generated from each function template arecombined with the set of non-template candidate functions.13.3.1.1 Function call syntax1[over.match.call]Recall from 5.2.2, that a function call is a postfix-expression, possibly nested arbitrarily deep in parentheses, followed by an optional expression-list enclosed in parentheses:(...(opt postfix-expression )...)opt (expression-listopt)Overload resolution is required if the postfix-expression is the name of a function, a function template(14.5.5), an object of class type, or a set of pointers-to-function.213.3.1.1.1 describes how overload resolution is used in the first two of the above cases to determine thefunction to call.

13.3.1.1.2 describes how overload resolution is used in the third of the above cases todetermine the function to call.3The fourth case arises from a postfix-expression of the form &F, where F names a set of overloaded functions. In the context of a function call, the set of functions named by F shall contain only non-memberfunctions and static member functions114). And in this context using &F behaves the same as using thename F by itself. Thus, (&F)(expression-listopt) is simply (F)(expression-listopt), which is discussedin 13.3.1.1.1. (The resolution of &F in other contexts is described in 13.4.)13.3.1.1.1 Call to named function1[over.call.func]Of interest in 13.3.1.1.1 are only those function calls in which the postfix-expression ultimately contains aname that denotes one or more functions that might be called. Such a postfix-expression, perhaps nestedarbitrarily deep in parentheses, has one of the following forms:postfix-expression:postfix-expression .

id-expressionpostfix-expression -> id-expressionprimary-expressionThese represent two syntactic subcategories of function calls: qualified function calls and unqualified function calls.2In qualified function calls, the name to be resolved is an id-expression and is preceded by an -> or .

operator. Since the construct A->B is generally equivalent to (*A).B, the rest of clause 13 assumes, withoutloss of generality, that all member function calls have been normalized to the form that uses an object andthe . operator. Furthermore, clause 13 assumes that the postfix-expression that is the left operand of the .operator has type “cv T” where T denotes a class115). Under this assumption, the id-expression in the call islooked up as a member function of T following the rules for looking up names in classes (10.2).

If a__________________113) The process of argument deduction fully determines the parameter types of the template functions, i.e., the parameters of templatefunctions contain no template parameter types. Therefore the template functions can be treated as normal (non-template) functions forthe remainder of overload resolution.114) If F names a non-static member function, &F is a pointer-to-member, which cannot be used with the function call syntax.115) Note that cv-qualifiers on the type of objects are significant in overload resolution for both lvalue and class rvalue objects.214© ISO/IEC13 OverloadingISO/IEC 14882:1998(E)13.3.1.1.1 Call to named functionmember function is found, that function and its overloaded declarations constitute the set of candidate functions. The argument list is the expression-list in the call augmented by the addition of the left operand ofthe .

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

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

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

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