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

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

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

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

]8.5.2 Character arrays1[dcl.init.string]A char array (whether plain char, signed char, or unsigned char) can be initialized by a stringliteral (optionally enclosed in braces); a wchar_t array can be initialized by a wide string-literal (optionally enclosed in braces); successive characters of the string-literal initialize the members of the array.[Example:char msg[] = "Syntax error on line %s\n";shows a character array whose members are initialized with a string-literal. Note that because ’\n’ is asingle character and because a trailing ’\0’ is appended, sizeof(msg) is 25.

]2There shall not be more initializers than there are array elements. [Example:char cv[4] = "asdf";// erroris ill-formed since there is no space for the implied trailing ’\0’. ]146© ISO/IECISO/IEC 14882:1998(E)8 Declarators8.5.2 Character arrays8.5.3 References1[dcl.init.ref]A variable declared to be a T&, that is “reference to type T” (8.3.2), shall be initialized by an object, orfunction, of type T or by an object that can be converted into a T.

[Example:int g(int);void f(){int i;int& r = i;r = 1;int* p = &r;int& rr = r;int (&rg)(int) = g;rg(i);int a[3];int (&ra)[3] = a;ra[1] = i;}// r refers to i// the value of i becomes 1// p points to i// rr refers to what r refers to, that is, to i// rg refers to the function g// calls function g// ra refers to the array a// modifies a[1]—end example]2A reference cannot be changed to refer to another object after initialization. Note that initialization of a reference is treated very differently from assignment to it. Argument passing (5.2.2) and function value return(6.6.3) are initializations.3The initializer can be omitted for a reference only in a parameter declaration (8.3.5), in the declaration of afunction return type, in the declaration of a class member within its class declaration (9.2), and where theextern specifier is explicitly used.

[Example:int& r1;extern int& r2;// error: initializer missing// OK—end example]4Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is reference-related to “cv2 T2” if T1 is the same type asT2, or T1 is a base class of T2. “cv1 T1” is reference-compatible with “cv2 T2” if T1 is reference-relatedto T2 and cv1 is the same cv-qualification as, or greater cv-qualification than, cv2.

For purposes of overload resolution, cases for which cv1 is greater cv-qualification than cv2 are identified as referencecompatible with added qualification (see 13.3.3.2). In all cases where the reference-related or referencecompatible relationship of two types is used to establish the validity of a reference binding, and T1 is a baseclass of T2, a program that necessitates such a binding is ill-formed if T1 is an inaccessible (clause 11) orambiguous (10.2) base class of T2.5A reference to type “cv1 T1” is initialized by an expression of type “cv2 T2” as follows:— If the initializer expression— is an lvalue (but is not a bit-field), and “cv1 T1” is reference-compatible with “cv2 T2,” or— has a class type (i.e., T2 is a class type) and can be implicitly converted to an lvalue of type“cv3 T3,” where “cv1 T1” is reference-compatible with “cv3 T3” 92) (this conversion is selected byenumerating the applicable conversion functions (13.3.1.6) and choosing the best one through overload resolution (13.3)),then the reference is bound directly to the initializer expression lvalue in the first case, and the referenceis bound to the lvalue result of the conversion in the second case.

In these cases the reference is said tobind directly to the initializer expression. [Note: the usual lvalue-to-rvalue (4.1), array-to-pointer (4.2),and function-to-pointer (4.3) standard conversions are not needed, and therefore are suppressed, whensuch direct bindings to lvalues are done. ]__________________92) This requires a conversion function (12.3.2) returning a reference type.147ISO/IEC 14882:1998(E)© ISO/IEC8.5.3 References8 Declarators[Example:double d = 2.0;double& rd = d;const double& rcd = d;// rd refers to d// rcd refers to dstruct A { };struct B : public A { } b;A& ra = b;const A& rca = b;// ra refers to A sub-object in b// rca refers to A sub-object in b—end example]— Otherwise, the reference shall be to a non-volatile const type (i.e., cv1 shall be const).

[Example:double& rd2 = 2.0;int i = 2;double& rd3 = i;// error: not an lvalue and reference not const// error: type mismatch and reference not const—end example]— If the initializer expression is an rvalue, with T2 a class type, and “cv1 T1” is reference-compatiblewith “cv2 T2,” the reference is bound in one of the following ways (the choice is implementationdefined):— The reference is bound to the object represented by the rvalue (see 3.10) or to a sub-object withinthat object.— A temporary of type “cv1 T2” [sic] is created, and a constructor is called to copy the entirervalue object into the temporary. The reference is bound to the temporary or to a sub-objectwithin the temporary.93)The constructor that would be used to make the copy shall be callable whether or not the copy isactually done.

[Example:struct Astruct Bextern Bconst A&{ };: public A { } b;f();rca = f();// Either bound to the A sub-object of the B rvalue,// or the entire B object is copied and the reference// is bound to the A sub-object of the copy—end example]— Otherwise, a temporary of type “cv1 T1” is created and initialized from the initializer expressionusing the rules for a non-reference copy initialization (8.5). The reference is then bound to the temporary. If T1 is reference-related to T2, cv1 must be the same cv-qualification as, or greater cvqualification than, cv2; otherwise, the program is ill-formed. [Example:const double& rcd2 = 2;const volatile int cvi = 1;const int& r = cvi;// rcd2 refers to temporary with value 2.0// error: type qualifiers dropped—end example]6[Note: 12.2 describes the lifetime of temporaries bound to references. ]__________________93) Clearly, if the reference initialization being processed is one for the first argument of a copy constructor call, an implementationmust eventually choose the first alternative (binding without copying) to avoid infinite recursion.148© ISO/IECISO/IEC 14882:1998(E)9 Classes1[class]A class is a type.

Its name becomes a class-name (9.1) within its scope.class-name:identifiertemplate-idClass-specifiers and elaborated-type-specifiers (7.1.5.3) are used to make class-names. An object of a classconsists of a (possibly empty) sequence of members and base class objects.class-specifier:class-head { member-specificationopt }class-head:class-key identifieropt base-clauseoptclass-key nested-name-specifier identifier base-clauseoptclass-key nested-name-specifieropt template-id base-clauseoptclass-key:classstructunion2A class-name is inserted into the scope in which it is declared immediately after the class-name is seen.The class-name is also inserted into the scope of the class itself.

For purposes of access checking, theinserted class name is treated as if it were a public member name. A class-specifier is commonly referredto as a class definition. A class is considered defined after the closing brace of its class-specifier has beenseen even though its member functions are in general not yet defined.3Complete objects and member subobjects of class type shall have nonzero size.94) [Note: class objects canbe assigned, passed as arguments to functions, and returned by functions (except objects of classes forwhich copying has been restricted; see 12.8).

Other plausible operators, such as equality comparison, canbe defined by the user; see 13.5. ]4A structure is a class defined with the class-key struct; its members and base classes (clause 10) are public by default (clause 11). A union is a class defined with the class-key union; its members are public bydefault and it holds only one data member at a time (9.5).

[Note: aggregates of class type are described in8.5.1. ] A POD-struct is an aggregate class that has no non-static data members of type pointer to member,non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-defined copy assignment operator and no user-defined destructor. Similarly, a POD-union is an aggregate union that has nonon-static data members of type pointer to member, non-POD-struct, non-POD-union (or array of suchtypes) or reference, and has no user-defined copy assignment operator and no user-defined destructor.

APOD class is a class that is either a POD-struct or a POD-union.9.1 Class names1[class.name]A class definition introduces a new type. [Example:__________________94) Base class subobjects are not so constrained.149ISO/IEC 14882:1998(E)© ISO/IEC9.1 Class names9 Classesstruct X { int a; };struct Y { int a; };X a1;Y a2;int a3;declares three variables of three different types. This implies thata1 = a2;a1 = a3;// error: Y assigned to X// error: int assigned to Xare type mismatches, and thatint f(X);int f(Y);declare an overloaded (clause 13) function f() and not simply a single function f() twice.

For the samereason,struct S { int a; };struct S { int a; };// error, double definitionis ill-formed because it defines S twice. ]2A class definition introduces the class name into the scope where it is defined and hides any class, object,function, or other declaration of that name in an enclosing scope (3.3). If a class name is declared in ascope where an object, function, or enumerator of the same name is also declared, then when both declarations are in scope, the class can be referred to only using an elaborated-type-specifier (3.4.4). [Example:struct stat {// ...};stat gstat;// use plain stat to// define variableint stat(struct stat*);// redeclare stat as functionvoid f(){struct stat* ps;stat(ps);// struct prefix needed// to name struct stat// ...// call stat()// ...}—end example] A declaration consisting solely of class-key identifier ; is either a redeclaration of thename in the current scope or a forward declaration of the identifier as a class name.

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

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

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

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