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

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

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

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

In the definition at namespace scope, the nameof the static data member shall be qualified by its class name using the :: operator. The initializerexpression in the definition of a static data member is in the scope of its class (3.3.6). [Example:class process {static process* run_chain;static process* running;};process* process::running = get_main();process* process::run_chain = running;The static data member run_chain of class process is defined in global scope; the notationprocess::run_chain specifies that the member run_chain is a member of class process and inthe scope of class process.

In the static data member definition, the initializer expression refers tothe static data member running of class process. ]3[Note: once the static data member has been defined, it exists even if no objects of its class have beencreated. [Example: in the example above, run_chain and running exist even if no objects of classprocess are created by the program. ] ]157ISO/IEC 14882:1998(E)© ISO/IEC9.4.2 Static data members9 Classes4If a static data member is of const integral or const enumeration type, its declaration in the classdefinition can specify a constant-initializer which shall be an integral constant expression (5.19). In thatcase, the member can appear in integral constant expressions within its scope.

The member shall still bedefined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.5There shall be exactly one definition of a static data member that is used in a program; no diagnostic isrequired; see 3.2. Unnamed classes and classes contained directly or indirectly within unnamed classesshall not contain static data members. [Note: this is because there is no mechanism to provide the definitions for such static data members.

]6Static data members of a class in namespace scope have external linkage (3.5). A local class shall nothave static data members.7Static data members are initialized and destroyed exactly like non-local objects (3.6.2, 3.6.3).8A static data member shall not be mutable (7.1.1).9.5 Unions[class.union]1In a union, at most one of the data members can be active at any time, that is, the value of at most one ofthe data members can be stored in a union at any time. [Note: one special guarantee is made in order tosimplify the use of unions: If a POD-union contains several POD-structs that share a common initialsequence (9.2), and if an object of this POD-union type contains one of the POD-structs, it is permitted toinspect the common initial sequence of any of POD-struct members; see 9.2.

] The size of a union is sufficient to contain the largest of its data members. Each data member is allocated as if it were the sole member of a struct. A union can have member functions (including constructors and destructors), but not virtual(10.3) functions. A union shall not have base classes. A union shall not be used as a base class. An objectof a class with a non-trivial constructor (12.1), a non-trivial copy constructor (12.8), a non-trivial destructor(12.4), or a non-trivial copy assignment operator (13.5.3, 12.8) cannot be a member of a union, nor can anarray of such objects.

If a union contains a static data member, or a member of reference type, the program is ill-formed.2A union of the formunion { member-specification } ;is called an anonymous union; it defines an unnamed object of unnamed type. The member-specification ofan anonymous union shall only define non-static data members. [Note: nested types and functions cannotbe declared within an anonymous union. ] The names of the members of an anonymous union shall be distinct from the names of any other entity in the scope in which the anonymous union is declared. For thepurpose of name lookup, after the anonymous union definition, the members of the anonymous union areconsidered to have been defined in the scope in which the anonymous union is declared.

[Example:void f(){union { int a; char* p; };a = 1;// ...p = "Jennifer";// ...}Here a and p are used like ordinary (nonmember) variables, but since they are union members they havethe same address. ]3Anonymous unions declared in a named namespace or in the global namespace shall be declared static.Anonymous unions declared at block scope shall be declared with any storage class allowed for a blockscope variable, or with no storage class. A storage class is not allowed in a declaration of an anonymousunion in a class scope. An anonymous union shall not have private or protected members (clause11).

An anonymous union shall not have function members.158© ISO/IECISO/IEC 14882:1998(E)9 Classes49.5 UnionsA union for which objects or pointers are declared is not an anonymous union. [Example:union { int aa; char* p; } obj, *ptr = &obj;aa = 1;// errorptr->aa = 1;// OKThe assignment to plain aa is ill formed since the member name is not visible outside the union, and evenif it were visible, it is not associated with any particular object. ] [Note: Initialization of unions with nouser-declared constructors is described in (8.5.1).

]9.6 Bit-fields1[class.bit]A member-declarator of the formidentifieropt : constant-expressionspecifies a bit-field; its length is set off from the bit-field name by a colon. The bit-field attribute is not partof the type of the class member. The constant-expression shall be an integral constant-expression with avalue greater than or equal to zero. The constant-expression may be larger than the number of bits in theobject representation (3.9) of the bit-field’s type; in such cases the extra bits are used as padding bits and donot participate in the value representation (3.9) of the bit-field. Allocation of bit-fields within a class objectis implementation-defined. Alignment of bit-fields is implementation-defined.

Bit-fields are packed intosome addressable allocation unit. [Note: bit-fields straddle allocation units on some machines and not onothers. Bit-fields are assigned right-to-left on some machines, left-to-right on others. ]2A declaration for a bit-field that omits the identifier declares an unnamed bit-field. Unnamed bit-fields arenot members and cannot be initialized. [Note: an unnamed bit-field is useful for padding to conform toexternally-imposed layouts. ] As a special case, an unnamed bit-field with a width of zero specifies alignment of the next bit-field at an allocation unit boundary.

Only when declaring an unnamed bit-field maythe constant-expression be a value equal to zero.3A bit-field shall not be a static member. A bit-field shall have integral or enumeration type (3.9.1). It isimplementation-defined whether a plain (neither explicitly signed nor unsigned) char, short, int orlong bit-field is signed or unsigned. A bool value can successfully be stored in a bit-field of any nonzerosize. The address-of operator & shall not be applied to a bit-field, so there are no pointers to bit-fields.

Anon-const reference shall not be bound to a bit-field (8.5.3). [Note: if the initializer for a reference of typeconst T& is an lvalue that refers to a bit-field, the reference is bound to a temporary initialized to hold thevalue of the bit-field; the reference is not bound to the bit-field directly. See 8.5.3. ]4If the value true or false is stored into a bit-field of type bool of any size (including a one bit bitfield), the original bool value and the value of the bit-field shall compare equal. If the value of an enumerator is stored into a bit-field of the same enumeration type and the number of bits in the bit-field is largeenough to hold all the values of that enumeration type, the original enumerator value and the value of thebit-field shall compare equal.

[Example:enum BOOL { f=0, t=1 };struct A {BOOL b:1;};A a;void f() {a.b = t;if (a.b == t){ /* ... */ }}// shall yield true—end example]159ISO/IEC 14882:1998(E)© ISO/IEC9.7 Nested class declarations9 Classes9.7 Nested class declarations1[class.nest]A class can be defined within another class. A class defined within another is called a nested class. Thename of a nested class is local to its enclosing class.

The nested class is in the scope of its enclosing class.Except by using explicit pointers, references, and object names, declarations in a nested class can use onlytype names, static members, and enumerators from the enclosing class. [Example:int x;int y;class enclose {public:int x;static int s;class inner {void f(int i){int a = sizeof(x);x = i;s = i;::x = i;y = i;}// error: refers to enclose::x// error: assign to enclose::x// OK: assign to enclose::s// OK: assign to global x// OK: assign to global yvoid g(enclose* p, int i){p->x = i;// OK: assign to enclose::x}};};inner* p = 0;// error: inner not in scope—end example]2Member functions and static data members of a nested class can be defined in a namespace scope enclosingthe definition of their class.

[Example:class enclose {public:class inner {static int x;void f(int i);};};int enclose::inner::x = 1;void enclose::inner::f(int i) { /* ... */ }—end example]3If class X is defined in a namespace scope, a nested class Y may be declared in class X and later defined inthe definition of class X or be later defined in a namespace scope enclosing the definition of class X.[Example:160© ISO/IECISO/IEC 14882:1998(E)9 Classes9.7 Nested class declarationsclass E {class I1;class I2;class I1 {};};class E::I2 {};// forward declaration of nested class// definition of nested class// definition of nested class—end example]4Like a member function, a friend function (11.4) defined within a nested class is in the lexical scope of thatclass; it obeys the same rules for name binding as a static member function of that class (9.4) and has nospecial access rights to members of an enclosing class.9.8 Local class declarations1[class.local]A class can be defined within a function definition; such a class is called a local class.

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

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

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

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