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

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

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

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

For another example,static int x3d[3][5][7];declares a static three-dimensional array of integers, with rank 3 × 5 × 7. In complete detail, x3d is an arrayof three items; each item is an array of five arrays; each of the latter arrays is an array of seven integers.Any of the expressions x3d, x3d[i], x3d[i][j], x3d[i][j][k] can reasonably appear in an expression.Finally,extern int x[10];struct S {static int y[10];};int x[];int S::y[];void f() {extern int x[];int i = sizeof(x);}// OK: bound is 10// OK: bound is 10// error: incomplete object type— end example ]5[ Note: conversions affecting expressions of array type are described in 4.2.

Objects of array types cannotbe modified, see 3.10. — end note ]6[ Note: Except where it has been declared for a class (13.5.5), the subscript operator [] is interpreted in sucha way that E1[E2] is identical to *((E1)+(E2)). Because of the conversion rules that apply to +, if E1 is anarray and E2 an integer, then E1[E2] refers to the E2-th member of E1. Therefore, despite its asymmetricappearance, subscripting is a commutative operation.7A consistent rule is followed for multidimensional arrays. If E is an n-dimensional array of rank i×j ×. . .×k,then E appearing in an expression that is subject to the array-to-pointer conversion (4.2) is converted to apointer to an (n − 1)-dimensional array with rank j × . .

. × k. If the * operator, either explicitly or implicitlyas a result of subscripting, is applied to this pointer, the result is the pointed-to (n − 1)-dimensional array,which itself is immediately converted into a pointer.8[ Example: considerint x[3][5];Here x is a 3 × 5 array of integers. When x appears in an expression, it is converted to a pointer to (thefirst of three) five-membered arrays of integers. In the expression x[i] which is equivalent to *(x+i), x isfirst converted to a pointer as described; then x+i is converted to the type of x, which involves multiplyingi by the length of the object to which the pointer points, namely five integer objects. The results are addedand indirection applied to yield an array (of five integers), which in turn is converted to a pointer to thefirst of the integers.

If there is another subscript the same argument applies again; this time the result is aninteger. — end example ] — end note ]9[ Note: It follows from all this that arrays in C++ are stored row-wise (last subscript varies fastest) and thatthe first subscript in the declaration helps determine the amount of storage consumed by an array but playsno other part in subscript calculations. — end note ]8.3.51Functions[dcl.fct]In a declaration T D where D has the form§ 8.3.5© ISO/IEC 2011 – All rights reserved191ISO/IEC 14882:2011(E)D1 ( parameter-declaration-clause ) cv-qualifier-seqoptref-qualifieropt exception-specificationopt attribute-specifier-seqoptand the type of the contained declarator-id in the declaration T D1 is “derived-declarator-type-list T”, thetype of the declarator-id in D is “derived-declarator-type-list function of (parameter-declaration-clause ) cv-qualifierseqopt ref-qualifieropt returning T”.

The optional attribute-specifier-seq appertains to the function type.2In a declaration T D where D has the formD1 ( parameter-declaration-clause ) cv-qualifier-seqoptref-qualifieropt exception-specificationopt attribute-specifier-seqopt trailing-return-typeand the type of the contained declarator-id in the declaration T D1 is “derived-declarator-type-list T”, Tshall be the single type-specifier auto. The type of the declarator-id in D is “derived-declarator-type-listfunction of (parameter-declaration-clause) cv-qualifier-seq opt ref-qualifier opt returning trailing-return-type”.The optional attribute-specifier-seq appertains to the function type.3A type of either form is a function type.98parameter-declaration-clause:parameter-declaration-listopt ...optparameter-declaration-list , ...parameter-declaration-list:parameter-declarationparameter-declaration-list , parameter-declarationparameter-declaration:attribute-specifier-seqoptattribute-specifier-seqoptattribute-specifier-seqoptattribute-specifier-seqoptdecl-specifier-seqdecl-specifier-seqdecl-specifier-seqdecl-specifier-seqdeclaratordeclarator = initializer-clauseabstract-declaratoroptabstract-declaratoropt = initializer-clauseThe optional attribute-specifier-seq in a parameter-declaration appertains to the parameter.4The parameter-declaration-clause determines the arguments that can be specified, and their processing, whenthe function is called.

[ Note: the parameter-declaration-clause is used to convert the arguments specifiedon the function call; see 5.2.2. — end note ] If the parameter-declaration-clause is empty, the functiontakes no arguments. The parameter list (void) is equivalent to the empty parameter list. Except for thisspecial case, void shall not be a parameter type (though types derived from void, such as void*, can).If the parameter-declaration-clause terminates with an ellipsis or a function parameter pack (14.5.3), thenumber of arguments shall be equal to or greater than the number of parameters that do not have a defaultargument and are not function parameter packs. Where syntactically correct and where “...” is not part ofan abstract-declarator, “, ...” is synonymous with “...”.

[ Example: the declarationint printf(const char*, ...);declares a function that can be called with varying numbers and types of arguments.printf("hello world");printf("a=%d b=%d", a, b);However, the first argument must be of a type that can be converted to a const char* — end example ][ Note: The standard header <cstdarg> contains a mechanism for accessing arguments passed using theellipsis (see 5.2.2 and 18.10). — end note ]5A single name can be used for several different functions in a single scope; this is function overloading(Clause 13).

All declarations for a function shall agree exactly in both the return type and the parametertype-list. The type of a function is determined using the following rules. The type of each parameter98) As indicated by syntax, cv-qualifiers are a signficant component in function return types.§ 8.3.5192© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)(including function parameter packs) is determined from its own decl-specifier-seq and declarator. Afterdetermining the type of each parameter, any parameter of type “array of T” or “function returning T” isadjusted to be “pointer to T” or “pointer to function returning T,” respectively. After producing the listof parameter types, any top-level cv-qualifiers modifying a parameter type are deleted when forming thefunction type.

The resulting list of transformed parameter types and the presence or absence of the ellipsisor a function parameter pack is the function’s parameter-type-list. [ Note: This transformation does notaffect the types of the parameters. For example, int(*)(const int p, decltype(p)*) and int(*)(int,const int*) are identical types. — end note ]6A cv-qualifier-seq or a ref-qualifier shall only be part of:— the function type for a non-static member function,— the function type to which a pointer to member refers,— the top-level function type of a function typedef declaration or alias-declaration,— the type-id in the default argument of a type-parameter (14.1), or— the type-id of a template-argument for a type-parameter (14.2).The effect of a cv-qualifier-seq in a function declarator is not the same as adding cv-qualification on topof the function type. In the latter case, the cv-qualifiers are ignored.

[ Note: a function type that has acv-qualifier-seq is not a cv-qualified type; there are no cv-qualified function types. — end note ] [ Example:typedef void F();struct S {const F f;};// OK: equivalent to: void f();— end example ] The return type, the parameter-type-list, the ref-qualifier, and the cv-qualifier-seq, but notthe default arguments (8.3.6) or the exception specification (15.4), are part of the function type.

[ Note:Function types are checked during the assignments and initializations of pointers to functions, references tofunctions, and pointers to member functions. — end note ]7[ Example: the declarationint fseek(FILE*, long, int);declares a function taking three arguments of the specified types, and returning int (7.1.6). — end example ]8If the type of a parameter includes a type of the form “pointer to array of unknown bound of T” or “referenceto array of unknown bound of T,” the program is ill-formed.99 Functions shall not have a return type oftype array or function, although they may have a return type of type pointer or reference to such things.There shall be no arrays of functions, although there can be arrays of pointers to functions.9Types shall not be defined in return or parameter types. The type of a parameter or the return type for afunction definition shall not be an incomplete class type (possibly cv-qualified) unless the function definitionis nested within the member-specification for that class (including definitions in nested classes defined withinthe class).10A typedef of function type may be used to declare a function but shall not be used to define a function (8.4).[ Example:99) This excludes parameters of type “ptr-arr-seq T2” where T2 is “pointer to array of unknown bound of T” and where ptrarr-seq means any sequence of “pointer to” and “array of” derived declarator types.

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

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

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

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