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

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

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

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

[Example:class X {public:// ...operator int();};class Y : public X {public:// ...operator char();};void f(Y& a){if (a) {// ill-formed:// X::operator int() or Y::operator char()// ...}}—end example]12.3.1 Conversion by constructor1[class.conv.ctor]A constructor declared without the function-specifier explicit that can be called with a single parameterspecifies a conversion from the type of its first parameter to the type of its class.

Such a constructor iscalled a converting constructor. [Example:class X {// ...public:X(int);X(const char*, int =0);};189ISO/IEC 14882:1998(E)© ISO/IEC12.3.1 Conversion by constructorvoid f(X arg){X a = 1;X b = "Jessie";a = 2;f(3);}12 Special member functions// a = X(1)// b = X("Jessie",0)// a = X(2)// f(X(3))—end example]2An explicit constructor constructs objects just like non-explicit constructors, but does so only where thedirect-initialization syntax (8.5) or where casts (5.2.9, 5.4) are explicitly used. A default constructor maybe an explicit constructor; such a constructor will be used to perform default-initialization (8.5).

[Example:class Z {public:explicit Z();explicit Z(int);// ...};Z a;Z a1 = 1;Z a3 = Z(1);Z a2(1);Z* p = new Z(1);Z a4 = (Z)1;Z a5 = static_cast<Z>(1);// OK: default-initialization performed// error: no implicit conversion// OK: direct initialization syntax used// OK: direct initialization syntax used// OK: direct initialization syntax used// OK: explicit cast used// OK: explicit cast used—end example]3A copy-constructor (12.8) is a converting constructor.

An implicitly-declared copy constructor is not anexplicit constructor; it may be called for implicit type conversions.12.3.2 Conversion functions1[class.conv.fct]A member function of a class X with a name of the formconversion-function-id:operator conversion-type-idconversion-type-id:type-specifier-seq conversion-declaratoroptconversion-declarator:ptr-operator conversion-declaratoroptspecifies a conversion from X to the type specified by the conversion-type-id.

Such member functions arecalled conversion functions. Classes, enumerations, and typedef-names shall not be declared in the typespecifier-seq. Neither parameter types nor return type can be specified. The type of a conversion function(8.3.5) is “function taking no parameter returning conversion-type-id.” A conversion function is never usedto convert a (possibly cv-qualified) object to the (possibly cv-qualified) same object type (or a reference toit), to a (possibly cv-qualified) base class of that type (or a reference to it), or to (possibly cv-qualified)void.103)__________________103) Even though never directly called to perform a conversion, such conversion functions can be declared and can potentially bereached through a call to a virtual conversion function in a base class190© ISO/IECISO/IEC 14882:1998(E)12 Special member functions212.3.2 Conversion functions[Example:class X {// ...public:operator int();};void f(X a){int i = int(a);i = (int)a;i = a;}In all three cases the value assigned will be converted by X::operator int().

—end example]3User-defined conversions are not restricted to use in assignments and initializations. [Example:void g(X a, X b){int i = (a) ? 1+a : 0;int j = (a&&b) ? a+b : i;if (a) {}}// ...—end example]4The conversion-type-id shall not represent a function type nor an array type. The conversion-type-id in aconversion-function-id is the longest possible sequence of conversion-declarators. [Note: this preventsambiguities between the declarator operator * and its expression counterparts. [Example:&ac.operator int*i;// syntax error:// parsed as: &(ac.operator int *) i// not as: &(ac.operator int)*iThe * is the pointer declarator and not the multiplication operator. ] ]5Conversion functions are inherited.6Conversion functions can be virtual.12.4 Destructors[class.dtor]1A special declarator syntax using an optional function-specifier (7.1.2) followed by ~ followed by thedestructor’s class name followed by an empty parameter list is used to declare the destructor in a class definition.

In such a declaration, the ~ followed by the destructor’s class name can be enclosed in optionalparentheses; such parentheses are ignored. A typedef-name that names a class is a class-name (7.1.3); however, a typedef-name that names a class shall not be used as the identifier in the declarator for a destructordeclaration.2A destructor is used to destroy objects of its class type. A destructor takes no parameters, and no returntype can be specified for it (not even void). The address of a destructor shall not be taken. A destructorshall not be static. A destructor can be invoked for a const, volatile or const volatileobject. A destructor shall not be declared const, volatile or const volatile (9.3.2). const andvolatile semantics (7.1.5.1) are not applied on an object under destruction.

Such semantics stop beinginto effect once the destructor for the most derived object (1.8) starts.3If a class has no user-declared destructor, a destructor is declared implicitly. An implicitly-declareddestructor is an inline public member of its class. A destructor is trivial if it is an implicitly-declareddestructor and if:— all of the direct base classes of its class have trivial destructors and191ISO/IEC 14882:1998(E)12.4 Destructors© ISO/IEC12 Special member functions— for all of the non-static data members of its class that are of class type (or array thereof), each such classhas a trivial destructor.4Otherwise, the destructor is non-trivial.5An implicitly-declared destructor is implicitly defined when it is used to destroy an object of its class type(3.7).

A program is ill-formed if the class for which a destructor is implicitly defined has:— a non-static data member of class type (or array thereof) with an inaccessible destructor, or— a base class with an inaccessible destructor.Before the implicitly-declared destructor for a class is implicitly defined, all the implicitly-declareddestructors for its base classes and its nonstatic data members shall have been implicitly defined. [Note: animplicitly-declared destructor has an exception-specification (15.4). ]6A destructor for class X calls the destructors for X’s direct members, the destructors for X’s direct baseclasses and, if X is the type of the most derived class (12.6.2), its destructor calls the destructors for X’s virtual base classes. All destructors are called as if they were referenced with a qualified name, that is, ignoring any possible virtual overriding destructors in more derived classes.

Bases and members are destroyedin the reverse order of the completion of their constructor (see 12.6.2). A return statement (6.6.3) in adestructor might not directly return to the caller; before transferring control to the caller, the destructors forthe members and bases are called. Destructors for elements of an array are called in reverse order of theirconstruction (see 12.6).7A destructor can be declared virtual (10.3) or pure virtual (10.4); if any objects of that class or anyderived class are created in the program, the destructor shall be defined. If a class has a base class with avirtual destructor, its destructor (whether user- or implicitly- declared) is virtual.8[Note: some language constructs have special semantics when used during destruction; see 12.7.

]9A union member shall not be of a class type (or array thereof) that has a non-trivial destructor.10Destructors are invoked implicitly (1) for a constructed object with static storage duration (3.7.1) at program termination (3.6.3), (2) for a constructed object with automatic storage duration (3.7.2) when theblock in which the object is created exits (6.7), (3) for a constructed temporary object when the lifetime ofthe temporary object ends (12.2), (4) for a constructed object allocated by a new-expression (5.3.4), throughuse of a delete-expression (5.3.5), (5) in several situations due to the handling of exceptions (15.3). A program is ill-formed if an object of class type or array thereof is declared and the destructor for the class is notaccessible at the point of the declaration.

Destructors can also be invoked explicitly.11At the point of definition of a virtual destructor (including an implicit definition (12.8)), non-placementoperator delete shall be looked up in the scope of the destructor’s class (3.4.1) and if found shall be accessible and unambiguous. [Note: this assures that an operator delete corresponding to the dynamic type of anobject is available for the delete-expression (12.5). ]12In an explicit destructor call, the destructor name appears as a ~ followed by a type-name that names thedestructor’s class type.

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

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

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

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