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

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

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

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

] [Example:struct X {typedef int T;static T count;void f(T);};void X::f(T t = count) { }The member function f of class X is defined in global scope; the notation X::f specifies that the functionf is a member of class X and in the scope of class X. In the function definition, the parameter type T refersto the typedef member T declared in class X and the default argument count refers to the static data member count declared in class X. ]6A static local variable in a member function always refers to the same object, whether or not the member function is inline.7Member functions may be mentioned in friend declarations after their class has been defined.8Member functions of a local class shall be defined inline in their class definition, if they are defined at all.9[Note: a member function can be declared (but not defined) using a typedef for a function type. The resulting member function has exactly the same type as it would have if the function declarator were providedexplicitly, see 8.3.5.

For example,typedef void fv(void);typedef void fvc(void) const;struct S {fv memfunc1;void memfunc2();fvc memfunc3;};fv S::* pmfv1 = &S::memfunc1;fv S::* pmfv2 = &S::memfunc2;fvc S::* pmfv3 = &S::memfunc3;// equivalent to: void memfunc1(void);// equivalent to: void memfunc3(void) const;Also see 14.3. ]9.3.1 Nonstatic member functions1[class.mfct.nonstatic]A nonstatic member function may be called for an object of its class type, or for an object of a class derived(clause 10) from its class type, using the class member access syntax (5.2.5, 13.3.1.1). A nonstatic memberfunction may also be called directly using the function call syntax (5.2.2, 13.3.1.1)— from within the body of a member function of its class or of a class derived from its class, or— from a mem-initializer (12.6.2) for a constructor for its class or for a class derived from its class.If a nonstatic member function of a class X is called for an object that is not of type X, or of a type derivedfrom X, the behavior is undefined.2When an id-expression (5.1) that is not part of a class member access syntax (5.2.5) and not used to form apointer to member (5.3.1) is used in the body of a nonstatic member function of class X or used in themem-initializer for a constructor of class X, if name lookup (3.4.1) resolves the name in the id-expression toa nonstatic nontype member of class X or of a base class of X, the id-expression is transformed into a classmember access expression (5.2.5) using (*this) (9.3.2) as the postfix-expression to the left of the .operator.

The member name then refers to the member of the object for which the function is called. Similarly during name lookup, when an unqualified-id (5.1) used in the definition of a member function forclass X resolves to a static member, an enumerator or a nested type of class X or of a base class of X, the154© ISO/IEC9 ClassesISO/IEC 14882:1998(E)9.3.1 Nonstatic member functionsunqualified-id is transformed into a qualified-id (5.1) in which the nested-name-specifier names the class ofthe member function.

[Example:struct tnode {char tword[20];int count;tnode *left;tnode *right;void set(char*, tnode* l, tnode* r);};void tnode::set(char* w, tnode* l, tnode* r){count = strlen(w)+1;if (sizeof(tword)<=count)perror("tnode string too long");strcpy(tword,w);left = l;right = r;}void f(tnode n1, tnode n2){n1.set("abc",&n2,0);n2.set("def",0,0);}In the body of the member function tnode::set, the member names tword, count, left, andright refer to members of the object for which the function is called. Thus, in the calln1.set("abc",&n2,0), tword refers to n1.tword, and in the call n2.set("def",0,0), itrefers to n2.tword. The functions strlen, perror, and strcpy are not members of the classtnode and should be declared elsewhere.95) ]3A nonstatic member function may be declared const, volatile, or const volatile.

These cvqualifiers affect the type of the this pointer (9.3.2). They also affect the function type (8.3.5) of themember function; a member function declared const is a const member function, a member functiondeclared volatile is a volatile member function and a member function declared const volatile isa const volatile member function. [Example:struct X {void g() const;void h() const volatile;};X::g is a const member function and X::h is a const volatile member function. ]4A nonstatic member function may be declared virtual (10.3) or pure virtual (10.4).9.3.2 The this pointer[class.this]1In the body of a nonstatic (9.3) member function, the keyword this is a non-lvalue expression whosevalue is the address of the object for which the function is called. The type of this in a member functionof a class X is X*.

If the member function is declared const, the type of this is const X*, if the member function is declared volatile, the type of this is volatile X*, and if the member function isdeclared const volatile, the type of this is const volatile X*.2In a const member function, the object for which the function is called is accessed through a constaccess path; therefore, a const member function shall not modify the object and its non-static data members.

[Example:__________________95) See, for example, <cstring> (21.4).155ISO/IEC 14882:1998(E)© ISO/IEC9.3.2 The this pointer9 Classesstruct s {int a;int f() const;int g() { return a++; }int h() const { return a++; }};// errorint s::f() const { return a; }The a++ in the body of s::h is ill-formed because it tries to modify (a part of) the object for whichs::h() is called. This is not allowed in a const member function because this is a pointer to const;that is, *this has const type. ]3Similarly, volatile semantics (7.1.5.1) apply in volatile member functions when accessing theobject and its non-static data members.4A cv-qualified member function can be called on an object-expression (5.2.5) only if the object-expressionis as cv-qualified or less-cv-qualified than the member function. [Example:void k(s& x, const s& y){x.f();x.g();y.f();y.g();}// errorThe call y.g() is ill-formed because y is const and s::g() is a non-const member function, that is,s::g() is less-qualified than the object-expression y.

]5Constructors (12.1) and destructors (12.4) shall not be declared const, volatile or constvolatile. [Note: However, these functions can be invoked to create and destroy objects with cvqualified types, see (12.1) and (12.4). ]9.4 Static members[class.static]1A data or function member of a class may be declared static in a class definition, in which case it is astatic member of the class.2A static member s of class X may be referred to using the qualified-id expression X::s; it is not necessary to use the class member access syntax (5.2.5) to refer to a static member. A static member maybe referred to using the class member access syntax, in which case the object-expression is always evaluated. [Example:class process {public:static void reschedule();};process& g();void f(){process::reschedule();g().reschedule();}// OK: no object necessary// g() is called—end example] A static member may be referred to directly in the scope of its class or in the scope of aclass derived (clause 10) from its class; in this case, the static member is referred to as if a qualified-idexpression was used, with the nested-name-specifier of the qualified-id naming the class scope from whichthe static member is referenced.

[Example:156© ISO/IECISO/IEC 14882:1998(E)9 Classesint g();struct X {static int g();};struct Y : X {static int i;};int Y::i = g();9.4 Static members// equivalent to Y::g();—end example]3If an unqualified-id (5.1) is used in the definition of a static member following the member’sdeclarator-id, and name lookup (3.4.1) finds that the unqualified-id refers to a static member, enumerator, or nested type of the member’s class (or of a base class of the member’s class), the unqualified-id istransformed into a qualified-id expression in which the nested-name-specifier names the class scope fromwhich the member is referenced.

The definition of a static member shall not use directly the names ofthe nonstatic members of its class or of a base class of its class (including as operands of the sizeof operator). The definition of a static member may only refer to these members to form pointer to members(5.3.1) or with the class member access syntax (5.2.5).4Static members obey the usual class member access rules (clause 11). When used in the declaration of aclass member, the static specifier shall only be used in the member declarations that appear within themember-specification of the class declaration.

[Note: it cannot be specified in member declarations thatappear in namespace scope. ]9.4.1 Static member functions[class.static.mfct]1[Note: the rules described in 9.3 apply to static member functions. ]2[Note: a static member function does not have a this pointer (9.3.2). ] A static member functionshall not be virtual. There shall not be a static and a nonstatic member function with the same nameand the same parameter types (13.1).

A static member function shall not be declared const,volatile, or const volatile.9.4.2 Static data members[class.static.data]1A static data member is not part of the subobjects of a class. There is only one copy of a static datamember shared by all the objects of the class.2The declaration of a static data member in its class definition is not a definition and may be of anincomplete type other than cv-qualified void. The definition for a static data member shall appear in anamespace scope enclosing the member’s class definition.

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

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

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

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