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

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

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

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

Since the address of a bit-field (9.6) cannot be taken, apointer can never point to a bit-field. ]8.3.2 References1[dcl.ref]In a declaration T D where D has the form& D1and the type of the identifier in the declaration T D1 is “derived-declarator-type-list T,” then the type of theidentifier of D is “derived-declarator-type-list reference to T.” Cv-qualified references are ill-formed exceptwhen the cv-qualifiers are introduced through the use of a typedef (7.1.3) or of a template type argument(14.3), in which case the cv-qualifiers are ignored. [Example: intypedef int& A;const A aref = 3;// ill-formed;// non-const reference initialized with rvaluethe type of aref is “reference to int”, not “const reference to int”.

] [Note: a reference can bethought of as a name of an object. ] A declarator that specifies the type “reference to cv void” is ill-formed.2[Example:void f(double& a) { a += 3.14; }// ...double d = 0;f(d);declares a to be a reference parameter of f so the call f(d) will add 3.14 to d.int v[20];// ...int& g(int i) { return v[i]; }// ...g(3) = 7;declares the function g() to return a reference to an integer so g(3)=7 will assign 7 to the fourth elementof the array v. For another example,struct link {link* next;};link* first;void h(link*& p){p->next = first;first = p;p = 0;}// p is a reference to pointervoid k(){link* q = new link;h(q);}declares p to be a reference to a pointer to link so h(q) will leave q with the value zero. See also 8.5.3.]3It is unspecified whether or not a reference requires storage (3.7).132© ISO/IECISO/IEC 14882:1998(E)8 Declarators48.3.2 ReferencesThere shall be no references to references, no arrays of references, and no pointers to references.

The declaration of a reference shall contain an initializer (8.5.3) except when the declaration contains an explicitextern specifier (7.1.1), is a class member (9.2) declaration within a class declaration, or is the declaration of a parameter or a return type (8.3.5); see 3.1. A reference shall be initialized to refer to a valid objector function. [Note: in particular, a null reference cannot exist in a well-defined program, because the onlyway to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer,which causes undefined behavior. As described in 9.6, a reference cannot be bound directly to a bit-field.

]8.3.3 Pointers to members1[dcl.mptr]In a declaration T D where D has the form::opt nested-name-specifier * cv-qualifier-seqopt D1and the nested-name-specifier names a class, and the type of the identifier in the declaration T D1 is“derived-declarator-type-list T,” then the type of the identifier of D is “derived-declarator-type-list cvqualifier-seq pointer to member of class nested-name-specifier of type T.”2[Example:class X {public:void f(int);int a;};class Y;int X::* pmi = &X::a;void (X::* pmf)(int) = &X::f;double X::* pmd;char Y::* pmc;declares pmi, pmf, pmd and pmc to be a pointer to a member of X of type int, a pointer to a member of Xof type void(int), a pointer to a member of X of type double and a pointer to a member of Y of typechar respectively. The declaration of pmd is well-formed even though X has no members of typedouble.

Similarly, the declaration of pmc is well-formed even though Y is an incomplete type. pmi andpmf can be used like this:X obj;//...obj.*pmi = 7;(obj.*pmf)(7);// assign 7 to an integer// member of obj// call a function member of obj// with the argument 7—end example]3A pointer to member shall not point to a static member of a class (9.4), a member with reference type, or“cv void.” [Note: see also 5.3 and 5.5. The type “pointer to member” is distinct from the type “pointer”,that is, a pointer to member is declared only by the pointer to member declarator syntax, and never by thepointer declarator syntax.

There is no “reference-to-member” type in C++. ]8.3.4 Arrays1[dcl.array]In a declaration T D where D has the formD1 [constant-expressionopt]and the type of the identifier in the declaration T D1 is “derived-declarator-type-list T,” then the type of theidentifier of D is an array type. T is called the array element type; this type shall not be a reference type, the(possibly cv-qualified) type void, a function type or an abstract class type. If the constant-expression(5.19) is present, it shall be an integral constant expression and its value shall be greater than zero. Theconstant expression specifies the bound of (number of elements in) the array. If the value of the constant133ISO/IEC 14882:1998(E)© ISO/IEC8.3.4 Arrays8 Declaratorsexpression is N, the array has N elements numbered 0 to N-1, and the type of the identifier of D is“derived-declarator-type-list array of N T.” An object of array type contains a contiguously allocated nonempty set of N sub-objects of type T.

If the constant expression is omitted, the type of the identifier of D is“derived-declarator-type-list array of unknown bound of T,” an incomplete object type. The type“derived-declarator-type-list array of N T” is a different type from the type “derived-declarator-type-listarray of unknown bound of T,” see 3.9. Any type of the form “cv-qualifier-seq array of N T” is adjusted to“array of N cv-qualifier-seq T,” and similarly for “array of unknown bound of T.” [Example:typedef int A[5], AA[2][3];typedef const A CA;typedef const AA CAA;// type is ‘‘array of 5 const int’’// type is ‘‘array of 2 array of 3 const int’’—end example] [Note: an “array of N cv-qualifier-seq T” has cv-qualified type; such an array has internallinkage unless explicitly declared extern (7.1.5.1) and must be initialized as specified in 8.5.

]2An array can be constructed from one of the fundamental types (except void), from a pointer, from apointer to member, from a class, from an enumeration type, or from another array.3When several “array of” specifications are adjacent, a multidimensional array is created; the constantexpressions that specify the bounds of the arrays can be omitted only for the first member of the sequence.[Note: this elision is useful for function parameters of array types, and when the array is external and thedefinition, which allocates storage, is given elsewhere.

] The first constant-expression can also be omittedwhen the declarator is followed by an initializer (8.5). In this case the bound is calculated from the numberof initial elements (say, N) supplied (8.5.1), and the type of the identifier of D is “array of N T.”4[Example:float fa[17], *afp[17];declares an array of float numbers and an array of pointers to float numbers. 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 anexpression. ]5[Note: conversions affecting lvalues of array type are described in 4.2. Objects of array types cannot bemodified, see 3.10. ]6Except where it has been declared for a class (13.5.5), the subscript operator [] is interpreted in such a waythat 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 ranki× j× . . . ×k, then E appearing in an expression is converted to a pointer to an (n − 1 )-dimensional arraywith rank j× . . . ×k. If the * operator, either explicitly or implicitly as a result of subscripting, is applied tothis pointer, the result is the pointed-to (n − 1 )-dimensional array, which itself is immediately convertedinto 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 (the firstof 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 the firstof the integers.

If there is another subscript the same argument applies again; this time the result is an integer. ]134© ISO/IECISO/IEC 14882:1998(E)8 Declarators98.3.4 Arrays[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.

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

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

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

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