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

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

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

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

The name of a localclass is local to its enclosing scope. The local class is in the scope of the enclosing scope, and has the sameaccess to names outside the function as does the enclosing function. Declarations in a local class can useonly type names, static variables, extern variables and functions, and enumerators from the enclosingscope. [Example:int x;void f(){static int s ;int x;extern int g();struct local {int g() { returnint h() { returnint k() { returnint l() { return};// ...x; }// error: x is autos; }// OK::x; } // OKg(); } // OK}local* p = 0;// error: local not in scope—end example]2An enclosing function has no special access to members of the local class; it obeys the usual access rules(clause 11). Member functions of a local class shall be defined within their class definition, if they aredefined at all.3If class X is a local class a nested class Y may be declared in class X and later defined in the definition ofclass X or be later defined in the same scope as the definition of class X.

A class nested within a local classis a local class.4A local class shall not have static data members.9.9 Nested type names1[class.nested.type]Type names obey exactly the same scope rules as other names. In particular, type names defined within aclass definition cannot be used outside their class without qualification. [Example:161ISO/IEC 14882:1998(E)© ISO/IEC9.9 Nested type names9 Classesclass X {public:typedef int I;class Y { /* ... */ };I a;};I b;Y c;X::Y d;X::I e;—end example]162// error// error// OK// OK© ISO/IEC10 Derived classes1ISO/IEC 14882:1998(E)[class.derived]A list of base classes can be specified in a class definition using the notation:base-clause:: base-specifier-listbase-specifier-list:base-specifierbase-specifier-list , base-specifierbase-specifier:::opt nested-name-specifieropt class-namevirtual access-specifieropt ::opt nested-name-specifieropt class-nameaccess-specifier virtualopt ::opt nested-name-specifieropt class-nameaccess-specifier:privateprotectedpublicThe class-name in a base-specifier shall not be an incompletely defined class (clause 9); this class is calleda direct base class for the class being declared.

During the lookup for a base class name, non-type namesare ignored (3.3.7). If the name found is not a class-name, the program is ill-formed. A class B is a baseclass of a class D if it is a direct base class of D or a direct base class of one of D’s base classes. A class isan indirect base class of another if it is a base class but not a direct base class. A class is said to be (directlyor indirectly) derived from its (direct or indirect) base classes. [Note: See clause 11 for the meaning ofaccess-specifier. ] Unless redefined in the derived class, members of a base class are also considered to bemembers of the derived class.

The base class members are said to be inherited by the derived class. Inherited members can be referred to in expressions in the same manner as other members of the derived class,unless their names are hidden or ambiguous (10.2). [Note: the scope resolution operator :: (5.1) can beused to refer to a direct or indirect base member explicitly. This allows access to a name that has beenredefined in the derived class. A derived class can itself serve as a base class subject to access control; see11.2. A pointer to a derived class can be implicitly converted to a pointer to an accessible unambiguousbase class (4.10).

An lvalue of a derived class type can be bound to a reference to an accessible unambiguous base class (8.5.3). ]2The base-specifier-list specifies the type of the base class subobjects contained in an object of the derivedclass type. [Example:class Base {public:int a, b, c;};class Derived : public Base {public:int b;};class Derived2 : public Derived {public:int c;};Here, an object of class Derived2 will have a sub-object of class Derived which in turn will have asub-object of class Base.

]163ISO/IEC 14882:1998(E)© ISO/IEC10 Derived classes310 Derived classesThe order in which the base class subobjects are allocated in the most derived object (1.8) is unspecified.[Note: a derived class and its base class sub-objects can be represented by a directed acyclic graph (DAG)where an arrow means “directly derived from.” A DAG of sub-objects is often referred to as a “sub-objectlattice.”BaseDerivedDerived2The arrows need not have a physical representation in memory.

]4[Note: initialization of objects representing base classes can be specified in constructors; see 12.6.2. ]5[Note: A base class subobject might have a layout (3.7) different from the layout of a most derived object ofthe same type. A base class subobject might have a polymorphic behavior (12.7) different from the polymorphic behavior of a most derived object of the same type. A base class subobject may be of zero size(clause 9); however, two subobjects that have the same class type and that belong to the same most derivedobject must not be allocated at the same address (5.10). ]10.1 Multiple base classes1[class.mi]A class can be derived from any number of base classes.

[Note: the use of more than one direct base classis often called multiple inheritance. ] [Example:classclassclassclassABCD{{{:/* .../* .../* ...public*/*/*/A,};};};public B, public C { /* ... */ };—end example]2[Note: the order of derivation is not significant except as specified by the semantics of initialization by constructor (12.6.2), cleanup (12.4), and storage layout (9.2, 11.1). ]3A class shall not be specified as a direct base class of a derived class more than once. [Note: a class can bean indirect base class more than once and can be a direct and an indirect base class. There are limitedthings that can be done with such a class.

The non-static data members and member functions of the directbase class cannot be referred to in the scope of the derived class. However, the static members, enumerations and types can be unambiguously referred to. ] [Example:class X { /* ... */ };class Y : public X, public X { /* ... */ };classclassclassclassclassLABCD{::::// ill-formedpublic: int next; /* ... */ };public L { /* ... */ };public L { /* ... */ };public A, public B { void f(); /* ...

*/ };public A, public L { void f(); /* ... */ };// well-formed// well-formed—end example]4A base class specifier that does not contain the keyword virtual, specifies a nonvirtual base class. Abase class specifier that contains the keyword virtual, specifies a virtual base class. For each distinctoccurrence of a nonvirtual base class in the class lattice of the most derived class, the most derived object(1.8) shall contain a corresponding distinct base class subobject of that type. For each distinct base classthat is specified virtual, the most derived object shall contain a single base class subobject of that type.[Example: for an object of class type C, each distinct occurrence of a (non-virtual) base class L in the classlattice of C corresponds one-to-one with a distinct L subobject within the object of type C.

Given the classC defined above, an object of class C will have two sub-objects of class L as shown below.164© ISO/IECISO/IEC 14882:1998(E)10 Derived classes10.1 Multiple base classesLLABCIn such lattices, explicit qualification can be used to specify which subobject is meant. The body of function C::f could refer to the member next of each L subobject:// well-formedvoid C::f() { A::next = B::next; }Without the A:: or B:: qualifiers, the definition of C::f above would be ill-formed because of ambiguity(10.2).5For another example,classclassclassclassVABC{:::/* ... */ };virtual public V { /* ...

*/ };virtual public V { /* ... */ };public A, public B { /* ... */ };for an object c of class type C, a single subobject of type V is shared by every base subobject of c that isdeclared to have a virtual base class of type V. Given the class C defined above, an object of class Cwill have one subobject of class V, as shown below.VABC6A class can have both virtual and nonvirtual base classes of a given type.classclassclassclassclassB { /* ... */ };X : virtual public B { /* ... */ };Y : virtual public B { /* ...

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

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

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

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