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

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

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

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

It is not used in the call to the selected function. Since the member functions all havethe same implicit object parameter, the contrived object will not be the cause to select or reject a function.128) Note that this construction can yield candidate call functions that cannot be differentiated one from the other by overloadresolution because they have identical declarations or differ only in their return type. The call will be ambiguous if overloadresolution cannot select a match to the call that is uniquely better than such undifferentiable functions.§ 13.3.1.1.2296© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)— end example ]13.3.1.21Operators in expressions[over.match.oper]If no operand of an operator in an expression has a type that is a class or an enumeration, the operatoris assumed to be a built-in operator and interpreted according to Clause 5.

[ Note: Because ., .*, and ::cannot be overloaded, these operators are always built-in operators interpreted according to Clause 5. ?:cannot be overloaded, but the rules in this subclause are used to determine the conversions to be applied tothe second and third operands when they have class or enumeration type (5.16).

— end note ] [ Example:struct String {String (const String&);String (const char*);operator const char* ();};String operator + (const String&, const String&);void f(void) {const char* p= "one" + "two";int I = 1 + 1;//////////ill-formed because neitheroperand has user-defined typeAlways evaluates to 2 even ifuser-defined types exist whichwould perform the operation.}— end example ]2If either operand has a type that is a class or an enumeration, a user-defined operator function might bedeclared that implements this operator or a user-defined conversion can be necessary to convert the operandto a type that is appropriate for a built-in operator. In this case, overload resolution is used to determinewhich operator function or built-in operator is to be invoked to implement the operator. Therefore, theoperator notation is first transformed to the equivalent function-call notation as summarized in Table 11(where @ denotes one of the operators covered in the specified subclause).Table 11 — Relationship between operator and function call notationSubclause13.5.113.5.213.5.313.5.513.5.613.5.73Expression@aa@ba=ba[b]a->a@As member function(a).operator@ ( )(a).operator@ (b)(a).operator= (b)(a).operator[](b)(a).operator-> ( )(a).operator@ (0)As non-member functionoperator@ (a)operator@ (a, b)operator@ (a, 0)For a unary operator @ with an operand of a type whose cv-unqualified version is T1, and for a binaryoperator @ with a left operand of a type whose cv-unqualified version is T1 and a right operand of a typewhose cv-unqualified version is T2, three sets of candidate functions, designated member candidates, nonmember candidates and built-in candidates, are constructed as follows:— If T1 is a complete class type, the set of member candidates is the result of the qualified lookup ofT1::operator@ (13.3.1.1.1); otherwise, the set of member candidates is empty.— The set of non-member candidates is the result of the unqualified lookup of operator@ in the contextof the expression according to the usual rules for name lookup in unqualified function calls (3.4.2)except that all member functions are ignored.

However, if no operand has a class type, only those§ 13.3.1.2© ISO/IEC 2011 – All rights reserved297ISO/IEC 14882:2011(E)non-member functions in the lookup set that have a first parameter of type T1 or “reference to (possiblycv-qualified) T1”, when T1 is an enumeration type, or (if there is a right operand) a second parameterof type T2 or “reference to (possibly cv-qualified) T2”, when T2 is an enumeration type, are candidatefunctions.— For the operator ,, the unary operator &, or the operator ->, the built-in candidates set is empty.For all other operators, the built-in candidates include all of the candidate operator functions definedin 13.6 that, compared to the given operator,— have the same operator name, and— accept the same number of operands, and— accept operand types to which the given operand or operands can be converted according to13.3.3.1, and— do not have the same parameter-type-list as any non-template non-member candidate.4For the built-in assignment operators, conversions of the left operand are restricted as follows:— no temporaries are introduced to hold the left operand, and— no user-defined conversions are applied to the left operand to achieve a type match with the left-mostparameter of a built-in candidate.5For all other operators, no such restrictions apply.6The set of candidate functions for overload resolution is the union of the member candidates, the non-membercandidates, and the built-in candidates.

The argument list contains all of the operands of the operator. Thebest function from the set of candidate functions is selected according to 13.3.2 and 13.3.3.129 [ Example:struct A {operator int();};A operator+(const A&, const A&);void m() {A a, b;a + b;// operator+(a,b) chosen over int(a) + int(b)}— end example ]7If a built-in candidate is selected by overload resolution, the operands are converted to the types of the corresponding parameters of the selected operation function. Then the operator is treated as the correspondingbuilt-in operator and interpreted according to Clause 5.8The second operand of operator -> is ignored in selecting an operator-> function, and is not an argumentwhen the operator-> function is called.

When operator-> returns, the operator -> is applied to the valuereturned, with the original second operand.1309If the operator is the operator ,, the unary operator &, or the operator ->, and there are no viable functions,then the operator is assumed to be the built-in operator and interpreted according to Clause 5.10[ Note: The lookup rules for operators in expressions are different than the lookup rules for operator functionnames in a function call, as shown in the following example:129) If the set of candidate functions is empty, overload resolution is unsuccessful.130) If the value returned by the operator-> function has class type, this may result in selecting and calling another operator->function.

The process repeats until an operator-> function returns a value of non-class type.§ 13.3.1.2298© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)struct A { };void operator + (A, A);struct B {void operator + (B);void f ();};A a;void B::f() {operator+ (a,a);a + a;}// error: global operator hidden by member// OK: calls global operator+— end note ]13.3.1.31[over.match.ctor]When objects of class type are direct-initialized (8.5), or copy-initialized from an expression of the same ora derived class type (8.5), overload resolution selects the constructor. For direct-initialization, the candidatefunctions are all the constructors of the class of the object being initialized.

For copy-initialization, thecandidate functions are all the converting constructors (12.3.1) of that class. The argument list is theexpression-list or assignment-expression of the initializer.13.3.1.41Initialization by constructorCopy-initialization of class by user-defined conversion[over.match.copy]Under the conditions specified in 8.5, as part of a copy-initialization of an object of class type, a user-definedconversion can be invoked to convert an initializer expression to the type of the object being initialized.Overload resolution is used to select the user-defined conversion to be invoked.

Assuming that “cv1 T” isthe type of the object being initialized, with T a class type, the candidate functions are selected as follows:— The converting constructors (12.3.1) of T are candidate functions.— When the type of the initializer expression is a class type “cv S”, the non-explicit conversion functions ofS and its base classes are considered. When initializing a temporary to be bound to the first parameterof a constructor that takes a reference to possibly cv-qualified T as its first argument, called with asingle argument in the context of direct-initialization, explicit conversion functions are also considered.Those that are not hidden within S and yield a type whose cv-unqualified version is the same type asT or is a derived class thereof are candidate functions.

Conversion functions that return “reference toX” return lvalues or xvalues, depending on the type of reference, of type X and are therefore consideredto yield X for this process of selecting candidate functions.2In both cases, the argument list has one argument, which is the initializer expression. [ Note: This argumentwill be compared against the first parameter of the constructors and against the implicit object parameterof the conversion functions.

— end note ]13.3.1.51Initialization by conversion function[over.match.conv]Under the conditions specified in 8.5, as part of an initialization of an object of nonclass type, a conversionfunction can be invoked to convert an initializer expression of class type to the type of the object beinginitialized. Overload resolution is used to select the conversion function to be invoked. Assuming that “cv1T” is the type of the object being initialized, and “cv S” is the type of the initializer expression, with S aclass type, the candidate functions are selected as follows:§ 13.3.1.5© ISO/IEC 2011 – All rights reserved299ISO/IEC 14882:2011(E)— The conversion functions of S and its base classes are considered. Those non-explicit conversionfunctions that are not hidden within S and yield type T or a type that can be converted to type Tvia a standard conversion sequence (13.3.3.1.1) are candidate functions.

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

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

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

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