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

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

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

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

— end example ]4A base-specifier followed by an ellipsis is a pack expansion (14.5.3).5The 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 subobjects can be represented by a directed acyclic graph (DAG)where an arrow means “directly derived from.” A DAG of subobjects is often referred to as a “subobjectlattice.”BaseDerived1Derived2Figure 2 — Directed acyclic graph6The arrows need not have a physical representation in memory.

— end note ]7[ Note: Initialization of objects representing base classes can be specified in constructors; see 12.6.2. — endnote ]8[ Note: A base class subobject might have a layout (3.7) different from the layout of a most derived objectof the same type. A base class subobject might have a polymorphic behavior (12.7) different from thepolymorphic behavior of a most derived object of the same type.

A base class subobject may be of zerosize (Clause 9); however, two subobjects that have the same class type and that belong to the same mostderived object must not be allocated at the same address (5.10). — end note ]10.11Multiple base classes[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. — end note ] [ 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 byconstructor (12.6.2), cleanup (12.4), and storage layout (9.2, 11.1). — end note ]3A class shall not be specified as a direct base class of a derived class more than once. [ Note: A class canbe an indirect base class more than once and can be a direct and an indirect base class. There are limited§ 10.1234© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)things 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, enumerationsand types can be unambiguously referred to. — end note ] [ Example:class X { /∗ ... ∗/ };class Y : public X, public X { /∗ ... ∗/ };classclassclassclassclassLABCD{::::public: int next;public L { /∗ ... ∗/public L { /∗ ... ∗/public A, public Bpublic A, public L// ill-formed/∗ ... ∗/ };};};{ void f(); /∗ ... ∗/ };{ void f(); /∗ ... ∗/ };// well-formed// well-formed— end example ]4A base class specifier that does not contain the keyword virtual, specifies a non-virtual base class. A baseclass specifier that contains the keyword virtual, specifies a virtual base class. For each distinct occurrenceof a non-virtual base class in the class lattice of the most derived class, the most derived object (1.8) shallcontain a corresponding distinct base class subobject of that type.

For each distinct base class that isspecified 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 class lattice ofC corresponds one-to-one with a distinct L subobject within the object of type C. Given the class C definedabove, an object of class C will have two subobjects of class L as shown below.LLABCFigure 3 — Non-virtual base5In such lattices, explicit qualification can be used to specify which subobject is meant.

The body of functionC::f could refer to the member next of each L subobject:void C::f() { A::next = B::next; }// well-formedWithout the A:: or B:: qualifiers, the definition of C::f above would be ill-formed because of ambiguity (10.2).6For 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 hasa virtual base class of type V. Given the class C defined above, an object of class C will have one subobjectof class V, as shown below.7A class can have both virtual and non-virtual base classes of a given type.§ 10.1© ISO/IEC 2011 – All rights reserved235ISO/IEC 14882:2011(E)VABCFigure 4 — Virtual baseclassclassclassclassclassB { /∗ ...

∗/ };X : virtual public B { /∗ ... ∗/ };Y : virtual public B { /∗ ... ∗/ };Z : public B { /∗ ... ∗/ };AA : public X, public Y, public Z { /∗ ... ∗/ };For an object of class AA, all virtual occurrences of base class B in the class lattice of AA correspond to asingle B subobject within the object of type AA, and every other occurrence of a (non-virtual) base class Bin the class lattice of AA corresponds one-to-one with a distinct B subobject within the object of type AA.Given the class AA defined above, class AA has two subobjects of class B: Z’s B and the virtual B shared by Xand Y, as shown below.BBYXZAAFigure 5 — Virtual and non-virtual base— end example ]10.2Member name lookup[class.member.lookup]1Member name lookup determines the meaning of a name (id-expression) in a class scope (3.3.7).

Namelookup can result in an ambiguity, in which case the program is ill-formed. For an id-expression, namelookup begins in the class scope of this; for a qualified-id, name lookup begins in the scope of the nestedname-specifier. Name lookup takes place before access control (3.4, Clause 11).2The following steps define the result of name lookup for a member name f in a class scope C.3The lookup set for f in C, called S(f, C), consists of two component sets: the declaration set, a set of membersnamed f; and the subobject set, a set of subobjects where declarations of these members (possibly includingusing-declarations) were found. In the declaration set, using-declarations are replaced by the members theydesignate, and type declarations (including injected-class-names) are replaced by the types they designate.S(f, C) is calculated as follows:§ 10.2236© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)4If C contains a declaration of the name f, the declaration set contains every declaration of f declared inC that satisfies the requirements of the language construct in which the lookup occurs.

[ Note: Lookingup a name in an elaborated-type-specifier (3.4.4) or base-specifier (Clause 10), for instance, ignores all nontype declarations, while looking up a name in a nested-name-specifier (3.4.3) ignores function, variable, andenumerator declarations. As another example, looking up a name in a using-declaration (7.3.3) includes thedeclaration of a class or enumeration that would ordinarily be hidden by another declaration of that namein the same scope. — end note ] If the resulting declaration set is not empty, the subobject set contains Citself, and calculation is complete.5Otherwise (i.e., C does not contain a declaration of f or the resulting declaration set is empty), S(f, C) isinitially empty. If C has base classes, calculate the lookup set for f in each direct base class subobject Bi ,and merge each such lookup set S(f, Bi ) in turn into S(f, C).6The following steps define the result of merging lookup set S(f, Bi ) into the intermediate S(f, C):— If each of the subobject members of S(f, Bi ) is a base class subobject of at least one of the subobjectmembers of S(f, C), or if S(f, Bi ) is empty, S(f, C) is unchanged and the merge is complete.

Conversely, if each of the subobject members of S(f, C) is a base class subobject of at least one of thesubobject members of S(f, Bi ), or if S(f, C) is empty, the new S(f, C) is a copy of S(f, Bi ).— Otherwise, if the declaration sets of S(f, Bi ) and S(f, C) differ, the merge is ambiguous: the newS(f, C) is a lookup set with an invalid declaration set and the union of the subobject sets.

In subsequentmerges, an invalid declaration set is considered different from any other.— Otherwise, the new S(f, C) is a lookup set with the shared set of declarations and the union of thesubobject sets.7The result of name lookup for f in C is the declaration set of S(f, C). If it is an invalid set, the program isill-formed. [ Example:struct A { int x; };struct B { float x; };struct C: public A, publicstruct D: public virtual Cstruct E: public virtual Cstruct F: public D, publicint main() {F f;f.x = 0;}B{{E////{ };//};//char x; }; //{ };//S(x,A) = { { A::x },S(x,B) = { { B::x },S(x,C) = { invalid, {S(x,D) = S(x,C)S(x,E) = { { E::x },S(x,F) = S(x,E){ A}}{ B}}A in C, B in C } }{ E}}// OK, lookup finds E::xS(x, F ) is unambiguous because the A and B base subobjects of D are also base subobjects of E, so S(x, D)is discarded in the first merge step.

— end example ]8If the name of an overloaded function is unambiguously found, overloading resolution (13.3) also takesplace before access control. Ambiguities can often be resolved by qualifying a name with its class name.[ Example:struct A {int f();};struct B {int f();};§ 10.2© ISO/IEC 2011 – All rights reserved237ISO/IEC 14882:2011(E)struct C : A, B {int f() { return A::f() + B::f(); }};— end example ]9[ Note: A static member, a nested type or an enumerator defined in a base class T can unambiguously befound even if an object has more than one base class subobject of type T.

Two base class subobjects sharethe non-static member subobjects of their common virtual base classes. — end note ] [ Example:struct Vint v;};struct Aint a;staticenum {};struct Bstruct Cstruct D{{inte };s;: A, virtual V { };: A, virtual V { };: B, C { };void f(D* pd) {pd->v++;pd->s++;int i = pd->e;pd->a++;}////////OK: only one v (virtual)OK: only one s (static)OK: only one e (enumerator)error, ambiguous: two as in D— end example ]10[ Note: When virtual base classes are used, a hidden declaration can be reached along a path through thesubobject lattice that does not pass through the hiding declaration. This is not an ambiguity.

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

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

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

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