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

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

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

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

[ Example:struct X {Z operator[](std::initializer_list<int>);};X x;x[{1,2,3}] = 7;// OK: meaning x.operator[]({1,2,3})int a[10];a[{1,2,3}] = 7;// error: built-in subscript operator— end example ]13.5.61Class member access[over.ref ]operator-> shall be a non-static member function taking no parameters. It implements the class memberaccess syntax that uses ->.postfix-expression -> templateopt id-expressionpostfix-expression -> pseudo-destructor-name§ 13.5.6© ISO/IEC 2011 – All rights reserved315ISO/IEC 14882:2011(E)An expression x->m is interpreted as (x.operator->())->m for a class object x of type T if T::operator->()exists and if the operator is selected as the best match function by the overload resolution mechanism (13.3).13.5.71Increment and decrement[over.inc]The user-defined function called operator++ implements the prefix and postfix ++ operator.

If this function isa member function with no parameters, or a non-member function with one parameter of class or enumerationtype, it defines the prefix increment operator ++ for objects of that type. If the function is a member functionwith one parameter (which shall be of type int) or a non-member function with two parameters (the secondof which shall be of type int), it defines the postfix increment operator ++ for objects of that type.

Whenthe postfix increment is called as a result of using the ++ operator, the int argument will have value zero.136[ Example:struct X {X&operator++();Xoperator++(int);};// prefix ++a// postfix a++struct Y { };Y&operator++(Y&);Yoperator++(Y&, int);// prefix ++b// postfix b++void f(X a, Y b) {++a;a++;++b;b++;////////a.operator++();a.operator++(0);operator++(b);operator++(b, 0);////////explicitexplicitexplicitexplicita.operator++();a.operator++(0);operator++(b);operator++(b, 0);call:call:call:call:likelikelikelike++a;a++;++b;b++;}— end example ]2The prefix and postfix decrement operators -- are handled analogously.13.5.8User-defined literals[over.literal]literal-operator-id:operator "" identifier1The identifier in a literal-operator-id is called a literal suffix identifier. [ Note: some literal suffix identifiersare reserved for future standardization; see 17.6.4.3.5.

— end note ]2A declaration whose declarator-id is a literal-operator-id shall be a declaration of a namespace-scope functionor function template (it could be a friend function (11.3)), an explicit instantiation or specialization of afunction template, or a using-declaration (7.3.3). A function declared with a literal-operator-id is a literaloperator.

A function template declared with a literal-operator-id is a literal operator template.3The declaration of a literal operator shall have a parameter-declaration-clause equivalent to one of thefollowing:136) Calling operator++ explicitly, as in expressions like a.operator++(2), has no special properties: The argument tooperator++ is 2.§ 13.5.8316© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)const char*unsigned long long intlong doublecharwchar_tchar16_tchar32_tconst char*, std::size_tconst wchar_t*, std::size_tconst char16_t*, std::size_tconst char32_t*, std::size_t4A raw literal operator is a literal operator with a single parameter whose type is const char*.5The declaration of a literal operator template shall have an empty parameter-declaration-clause and itstemplate-parameter-list shall have a single template-parameter that is a non-type template parameter pack(14.5.3) with element type char.6Literal operators and literal operator templates shall not have C language linkage.7[ Note: Literal operators and literal operator templates are usually invoked implicitly through user-definedliterals (2.14.8).

However, except for the constraints described above, they are ordinary namespace-scopefunctions and function templates. In particular, they are looked up like ordinary functions and function templates and they follow the same overload resolution rules. Also, they can be declared inline or constexpr,they may have internal or external linkage, they can be called explicitly, their addresses can be taken, etc.— end note ]8[ Example:void operator "" _km(long double);string operator "" _i18n(const char*, std::size_t);template <char...> int operator "" \u03C0();float operator ""E(const char*);float operator " "string operator ""double operator ""template <char...>B(const char*);5X(const char*, std::size_t);_miles(double);int operator "" j(const char*);//////////////////OKOKOK: UCN for lowercase pierror: ""E (with no intervening space)is a single tokenerror: non-adjacent quoteserror: invalid literal suffix identifiererror: invalid parameter-declaration-clauseerror: invalid parameter-declaration-clause— end example ]13.61Built-in operators[over.built]The candidate operator functions that represent the built-in operators defined in Clause 5 are specified inthis subclause.

These candidate functions participate in the operator overload resolution process as describedin 13.3.1.2 and are used for no other purpose. [ Note: Because built-in operators take only operands withnon-class type, and operator overload resolution occurs only when an operand expression originally has classor enumeration type, operator overload resolution can resolve to a built-in operator only when an operandhas a class type that has a user-defined conversion to a non-class type appropriate for the operator, or whenan operand has an enumeration type that can be converted to a type appropriate for the operator. Also notethat some of the candidate operator functions given in this subclause are more permissive than the built-inoperators themselves.

As described in 13.3.1.2, after a built-in operator is selected by overload resolutionthe expression is subject to the requirements for the built-in operator given in Clause 5, and therefore toany additional semantic constraints given there. If there is a user-written candidate with the same nameand parameter types as a built-in candidate operator function, the built-in operator function is hidden andis not included in the set of candidate functions. — end note ]§ 13.6© ISO/IEC 2011 – All rights reserved317ISO/IEC 14882:2011(E)2In this subclause, the term promoted integral type is used to refer to those integral types which are preservedby integral promotion (including e.g. int and long but excluding e.g.

char). Similarly, the term promotedarithmetic type refers to floating types plus promoted integral types. [ Note: In all cases where a promotedintegral type or promoted arithmetic type is required, an operand of enumeration type will be acceptableby way of the integral promotions. — end note ]3For every pair (T, VQ), where T is an arithmetic type, and VQ is either volatile or empty, there existcandidate operator functions of the formVQ T & operator++(VQ T &);T operator++(VQ T &, int);4For every pair (T, VQ), where T is an arithmetic type other than bool, and VQ is either volatile or empty,there exist candidate operator functions of the formVQ T & operator--(VQ T &);T operator--(VQ T &, int);5For every pair (T, VQ), where T is a cv-qualified or cv-unqualified object type, and VQ is either volatileor empty, there exist candidate operator functions of the formT *VQ&T *VQ&T*T*6For every cv-qualified or cv-unqualified object type T, there exist candidate operator functions of the formT&7operator*(T *);For every type T there exist candidate operator functions of the formT*9operator*(T *);For every function type T that does not have cv-qualifiers or a ref-qualifier, there exist candidate operatorfunctions of the formT&8operator++(T *VQ&);operator--(T *VQ&);operator++(T *VQ&, int);operator--(T *VQ&, int);operator+(T *);For every promoted arithmetic type T, there exist candidate operator functions of the formT operator+(T );T operator-(T );10For every promoted integral type T, there exist candidate operator functions of the formT operator∼(T );11For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, C1 is the same type as C2 or is aderived class of C2, T is an object type or a function type, and CV1 and CV2 are cv-qualifier-seqs, thereexist candidate operator functions of the formCV12 T & operator->*(CV1 C1*, CV2 T C2::*);where CV12 is the union of CV1 and CV2.12For every pair of promoted arithmetic types L and R, there exist candidate operator functions of the form§ 13.6318© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)operator*(L, R);operator/(L, R);operator+(L, R);operator-(L, R);operator<(L, R);operator>(L, R);operator<=(L, R);operator>=(L, R);operator==(L, R);operator!=(L, R);LRLRLRLRboolboolboolboolboolboolwhere LR is the result of the usual arithmetic conversions between types L and R.13For every cv-qualified or cv-unqualified object type T there exist candidate operator functions of the formT*T&T*T*T&14operator+(T *, std::ptrdiff_t);operator[](T *, std::ptrdiff_t);operator-(T *, std::ptrdiff_t);operator+(std::ptrdiff_t, T *);operator[](std::ptrdiff_t, T *);For every T, where T is a pointer to object type, there exist candidate operator functions of the formstd::ptrdiff_t15For every T , where T is an enumeration type, a pointer type, or std::nullptr_t, there exist candidateoperator functions of the formboolboolboolboolboolbool16operator<(T , T );operator>(T , T );operator<=(T , T );operator>=(T , T );operator==(T , T );operator!=(T , T );For every pointer to member type T there exist candidate operator functions of the formboolbool17operator-(T , T );operator==(T , T );operator!=(T , T );For every pair of promoted integral types L and R, there exist candidate operator functions of the formoperator%(L , R );operator&(L , R );operator^(L , R );operator|(L , R );operator<<(L , R );operator>>(L , R );LRLRLRLRLLwhere LR is the result of the usual arithmetic conversions between types L and R.18For every triple (L, VQ, R), where L is an arithmetic type, VQ is either volatile or empty, and R is apromoted arithmetic type, there exist candidate operator functions of the formVQVQVQVQVQLLLLL&&&&&operator=(VQ L &, R );operator*=(VQ L &, R );operator/=(VQ L &, R );operator+=(VQ L &, R );operator-=(VQ L &, R );§ 13.6© ISO/IEC 2011 – All rights reserved319ISO/IEC 14882:2011(E)19For every pair (T , VQ), where T is any type and VQ is either volatile or empty, there exist candidateoperator functions of the formT *VQ &20For every pair (T , VQ), where T is an enumeration or pointer to member type and VQ is either volatileor empty, there exist candidate operator functions of the formVQ T &21LLLLLL&&&&&&operator%=(VQ L &, R );operator<<=(VQ L &, R );operator>>=(VQ L &, R );operator&=(VQ L &, R );operator^=(VQ L &, R );operator|=(VQ L &, R );There also exist candidate operator functions of the formboolboolbool24operator+=(T *VQ &, std::ptrdiff_t);operator-=(T *VQ &, std::ptrdiff_t);For every triple (L, VQ, R), where L is an integral type, VQ is either volatile or empty, and R is apromoted integral type, there exist candidate operator functions of the formVQVQVQVQVQVQ23operator=(VQ T &, T );For every pair (T , VQ), where T is a cv-qualified or cv-unqualified object type and VQ is either volatileor empty, there exist candidate operator functions of the formT *VQ &T *VQ &22operator=(T *VQ &, T *);operator!(bool);operator&&(bool, bool);operator||(bool, bool);For every pair of promoted arithmetic types L and R, there exist candidate operator functions of the formLRoperator?:(bool, L , R );where LR is the result of the usual arithmetic conversions between types L and R.

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

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

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

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