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

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

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

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

A class is abstract if it has at leastone pure virtual function. [ Note: Such a function might be inherited: see below. — end note ] A virtualfunction is specified pure by using a pure-specifier (9.2) in the function declaration in the class definition. Apure virtual function need be defined only if called with, or as if with (12.4), the qualified-id syntax (5.1).[ Example:class point { /∗ ...

∗/ };class shape {// abstract classpoint center;public:point where() { return center; }void move(point p) { center=p; draw(); }virtual void rotate(int) = 0; // pure virtualvirtual void draw() = 0;// pure virtual};— end example ] [ Note: A function declaration cannot provide both a pure-specifier and a definition — endnote ] [ Example:struct C {virtual void f() = 0 { };};// ill-formed§ 10.4244© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)— end example ]3An abstract class shall not be used as a parameter type, as a function return type, or as the type of anexplicit conversion.

Pointers and references to an abstract class can be declared. [ Example:shape x;shape* p;shape f();void g(shape);shape& h(shape&);//////////error: object of abstract classOKerrorerrorOK— end example ]4A class is abstract if it contains or inherits at least one pure virtual function for which the final overrider ispure virtual. [ Example:class ab_circle : public shape {int radius;public:void rotate(int) { }// ab_circle::draw() is a pure virtual};Since shape::draw() is a pure virtual function ab_circle::draw() is a pure virtual by default.

Thealternative declaration,class circle : public shape {int radius;public:void rotate(int) { }void draw();};// a definition is required somewherewould make class circle nonabstract and a definition of circle::draw() must be provided. — end example ]5[ Note: An abstract class can be derived from a class that is not abstract, and a pure virtual function mayoverride a virtual function which is not pure.

— end note ]6Member functions can be called from a constructor (or destructor) of an abstract class; the effect of making avirtual call (10.3) to a pure virtual function directly or indirectly for the object being created (or destroyed)from such a constructor (or destructor) is undefined.§ 10.4© ISO/IEC 2011 – All rights reserved245ISO/IEC 14882:2011(E)111Member access control[class.access]A member of a class can be— private; that is, its name can be used only by members and friends of the class in which it is declared.— protected; that is, its name can be used only by members and friends of the class in which it isdeclared, by classes derived from that class, and by their friends (see 11.4).— public; that is, its name can be used anywhere without access restriction.2A member of a class can also access all the names to which the class has access.

A local class of a memberfunction may access the same names that the member function itself may access.1133Members of a class defined with the keyword class are private by default. Members of a class definedwith the keywords struct or union are public by default. [ Example:class X {int a;};// X::a is private by defaultstruct S {int a;};// S::a is public by default— end example ]4Access control is applied uniformly to all names, whether the names are referred to from declarations orexpressions. [ Note: Access control applies to names nominated by friend declarations (11.3) and usingdeclarations (7.3.3).

— end note ] In the case of overloaded function names, access control is applied to thefunction selected by overload resolution. [ Note: Because access control applies to names, if access control isapplied to a typedef name, only the accessibility of the typedef name itself is considered. The accessibilityof the entity referred to by the typedef is not considered. For example,class A {class B { };public:typedef B BB;};void f() {A::BB x;A::B y;}// OK, typedef name A::BB is public// access error, A::B is private— end note ]5It should be noted that it is access to members and base classes that is controlled, not their visibility.

Namesof members are still visible, and implicit conversions to base classes are still considered, when those membersand base classes are inaccessible. The interpretation of a given construct is established without regard to113) Access permissions are thus transitive and cumulative to nested and local classes.246© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)access control. If the interpretation established makes use of inaccessible member names or base classes, theconstruct is ill-formed.6All access controls in Clause 11 affect the ability to access a class member name from the declaration of aparticular entity, including parts of the declaration preceding the name of the entity being declared and, if theentity is a class, the definitions of members of the class appearing outside the class’s member-specification.[ Note: this access also applies to implicit references to constructors, conversion functions, and destructors.— end note ] [ Example:class A {typedef int I;// private memberI f();friend I g(I);static I x;template<int> struct Q;template<int> friend struct R;protected:struct B { };};A::I A::f() { return 0; }A::I g(A::I p = A::x);A::I g(A::I p) { return 0; }A::I A::x = 0;template<A::I> struct A::Q { };template<A::I> struct R { };struct D: A::B, A { };7Here, all the uses of A::I are well-formed because A::f, A::x, and A::Q are members of class A and g andR are friends of class A.

This implies, for example, that access checking on the first use of A::I must bedeferred until it is determined that this use of A::I is as the return type of a member of class A. Similarly,the use of A::B as a base-specifier is well-formed because D is derived from A, so checking of base-specifiersmust be deferred until the entire base-specifier-list has been seen. — end example ]8The names in a default argument (8.3.6) are bound at the point of declaration, and access is checked at thatpoint rather than at any points of use of the default argument. Access checking for default arguments infunction templates and in member functions of class templates is performed as described in 14.7.1.9The names in a default template-argument (14.1) have their access checked in the context in which theyappear rather than at any points of use of the default template-argument.

[ Example:class B { };template <class T> class C {protected:typedef T TT;};template <class U, class V = typename U::TT>class D : public U { };D <C<B> >* d;// access error, C::TT is protected— end example ]© ISO/IEC 2011 – All rights reserved247ISO/IEC 14882:2011(E)11.11Access specifiers[class.access.spec]Member declarations can be labeled by an access-specifier (Clause 10):access-specifier : member-specificationoptAn access-specifier specifies the access rules for members following it until the end of the class or untilanother access-specifier is encountered. [ Example:class X {int a;public:int b;int c;};// X::a is private by default: class used// X::b is public// X::c is public— end example ]2Any number of access specifiers is allowed and no particular order is required.

[ Example:struct S {int a;protected:int b;private:int c;public:int d;};// S::a is public by default: struct used// S::b is protected// S::c is private// S::d is public— end example ]3[ Note: The effect of access control on the order of allocation of data members is described in 9.2. — endnote ]4When a member is redeclared within its class definition, the access specified at its redeclaration shall be thesame as at its initial declaration. [ Example:struct S {class A;enum E : int;private:class A { };// error: cannot change accessenum E: int { e0 }; // error: cannot change access};— end example ]5[ Note: In a derived class, the lookup of a base class name will find the injected-class-name instead of thename of the base class in the scope in which it was declared.

The injected-class-name might be less accessiblethan the name of the base class in the scope in which it was declared. — end note ][ Example:class A { };class B : private A { };class C : public B {A *p;// error: injected-class-name A is inaccessible::A *q;// OK};§ 11.1248© ISO/IEC 2011 – All rights reservedISO/IEC 14882:2011(E)— end example ]11.2Accessibility of base classes and base class members[class.access.base]1If a class is declared to be a base class (Clause 10) for another class using the public access specifier, thepublic members of the base class are accessible as public members of the derived class and protectedmembers of the base class are accessible as protected members of the derived class.

If a class is declared tobe a base class for another class using the protected access specifier, the public and protected membersof the base class are accessible as protected members of the derived class. If a class is declared to be a baseclass for another class using the private access specifier, the public and protected members of the baseclass are accessible as private members of the derived class114 .2In the absence of an access-specifier for a base class, public is assumed when the derived class is defined withthe class-key struct and private is assumed when the class is defined with the class-key class.

[ Example:class B { /∗ ... ∗/ };class D1 : private B { /∗ ... ∗/ };class D2 : public B { /∗ ... ∗/ };class D3 : B { /∗ ... ∗/ };// B private by defaultstruct D4 : public B { /∗ ... ∗/ };struct D5 : private B { /∗ ... ∗/ };// B public by defaultstruct D6 : B { /∗ ... ∗/ };class D7 : protected B { /∗ ... ∗/ };struct D8 : protected B { /∗ ...

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

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

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

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