Главная » Просмотр файлов » B. Stroustrup - The C++ Programming Language

B. Stroustrup - The C++ Programming Language (794319), страница 74

Файл №794319 B. Stroustrup - The C++ Programming Language (B. Stroustrup - The C++ Programming Language) 74 страницаB. Stroustrup - The C++ Programming Language (794319) страница 742019-05-09СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

There are separate rules for overloading when a{}-list is used (initializer lists take priority; §12.2.3, §17.3.4.1) and for rvalue reference templatearguments (§23.5.2.1).Overloading relies on a relatively complicated set of rules, and occasionally a programmer willbe surprised which function is called. So, why bother? Consider the alternative to overloading.Often, we need similar operations performed on objects of several types.

Without overloading, wemust define several functions with different names:328FunctionsChapter 12void print_int(int);void print_char(char);void print_string(const char∗);// C-style stringvoid g(int i, char c, const char∗ p, double d){print_int(i);// OKprint_char(c);// OKprint_string(p);// OKprint_int(c);print_char(i);print_string(i);print_int(d);// OK? calls print_int(int(c)), prints a number// OK? calls print_char(char(i)), narrowing// error// OK? calls print_int(int(d)), narrowing}Compared to the overloaded print(), we have to remember several names and remember to use thosecorrectly. This can be tedious, defeats attempts to do generic programming (§4.5), and generallyencourages the programmer to focus on relatively low-level type issues. Because there is no overloading, all standard conversions apply to arguments to these functions.

It can also lead to errors.In the previous example, this implies that only one of the four calls with doubtful semantics iscaught by the compiler. In particular, two calls rely on error-prone narrowing (§2.2.2, §10.5).Thus, overloading can increase the chances that an unsuitable argument will be rejected by thecompiler.12.3.2 Overloading and Return TypeReturn types are not considered in overload resolution. The reason is to keep resolution for an individual operator (§18.2.1, §18.2.5) or function call context-independent. Consider:float sqrt(float);double sqrt(double);void f(double da, float fla){float fl = sqrt(da); // call sqrt(double)double d = sqrt(da); // call sqrt(double)fl = sqrt(fla);// call sqrt(float)d = sqrt(fla);// call sqrt(float)}If the return type were taken into account, it would no longer be possible to look at a call of sqrt() inisolation and determine which function was called.12.3.3 Overloading and ScopeOverloading takes place among the members of an overload set.

By default, that means the functions of a single scope; functions declared in different non-namespace scopes do not overload. Forexample:Section 12.3.3Overloading and Scope329void f(int);void g(){void f(double);f(1);// call f(double)}Clearly, f(int) would have been the best match for f(1), but only f(double) is in scope. In such cases,local declarations can be added or subtracted to get the desired behavior. As always, intentionalhiding can be a useful technique, but unintentional hiding is a source of surprises.A base class and a derived class provide different scopes so that overloading between a baseclass function and a derived class function doesn’t happen by default.

For example:struct Base {void f(int);};struct Derived : Base {void f(double);};void g(Derived& d){d.f(1);// call Derived::f(double);}When overloading across class scopes (§20.3.5) or namespace scopes (§14.4.5) is wanted, usingdeclarations or using-directives can be used (§14.2.2).

Argument-dependent lookup (§14.2.4) canalso lead to overloading across namespaces.12.3.4 Resolution for Multiple ArgumentsWe can use the overload resolution rules to select the most appropriate function when the efficiencyor precision of computations differs significantly among types. For example:int pow(int, int);double pow(double, double);complex pow(double, complex);complex pow(complex, int);complex pow(complex, complex);void k(complex z){int i = pow(2,2);double d = pow(2.0,2.0);complex z2 = pow(2,z);complex z3 = pow(z,2);complex z4 = pow(z,z);}// invoke pow(int,int)// invoke pow(double,double)// invoke pow(double,complex)// invoke pow(complex,int)// invoke pow(complex,complex)330FunctionsChapter 12In the process of choosing among overloaded functions with two or more arguments, a best matchis found for each argument using the rules from §12.3.

A function that is the best match for oneargument and a better or equal match for all other arguments is called. If no such function exists,the call is rejected as ambiguous. For example:void g(){double d = pow(2.0,2);}// error : pow(int(2.0),2) or pow(2.0,double(2))?The call is ambiguous because 2.0 is the best match for the first argument of pow(double,double) and2 is the best match for the second argument of pow(int,int).12.3.5 Manual Overload ResolutionDeclaring too few (or too many) overloaded versions of a function can lead to ambiguities. Forexample:void f1(char);void f1(long);void f2(char∗);void f2(int∗);void k(int i){f1(i);f2(0);}// ambiguous: f1(char) or f1(long)?// ambiguous: f2(char*) or f2(int*)?Where possible, consider the set of overloaded versions of a function as a whole and see if it makessense according to the semantics of the function.

Often the problem can be solved by adding a version that resolves ambiguities. For example, addinginline void f1(int n) { f1(long(n)); }would resolve all ambiguities similar to f1(i) in favor of the larger type long int.One can also add an explicit type conversion to resolve a specific call. For example:f2(static_cast<int∗>(0));However, this is most often simply an ugly stopgap. Soon another similar call will be made andhave to be dealt with.Some C++ novices get irritated by the ambiguity errors reported by the compiler.

More experienced programmers appreciate these error messages as useful indicators of design errors.12.4 Pre- and PostconditionsEvery function has some expectations on its arguments. Some of these expectations are expressedin the argument types, but others depend on the actual values passed and on relationships amongSection 12.4Pre- and Postconditions331argument values. The compiler and linker can ensure that arguments are of the right types, but it isup to the programmer to decide what to do about ‘‘bad’’ argument values. We call logical criteriathat are supposed to hold when a function is called preconditions, and logical criteria that are supposed to hold when a function returns its postconditions.

For example:int area(int len, int wid)/*calculate the area of a rectangleprecondition: len and wid are positivepostcondition: the return value is positivepostcondition: the return value is the area of a rectange with sides len and wid*/{return len∗wid;}Here, the statements of the pre- and postconditions are longer than the function body.

This mayseem excessive, but the information provided is useful to the implementer, to the users of area(),and to testers. For example, we learn that 0 and −12 are not considered valid arguments. Furthermore, we note that we could pass a couple of huge values without violating the precondition, but iflen∗wid overflows either or both of the postconditions are not met.What should we do about a call area(numeric_limits<int>::max(),2)?[1] Is it the caller’s task to avoid it? Yes, but what if the caller doesn’t?[2] Is it the implementer’s task to avoid it? If so, how is an error to be handled?There are several possible answers to these questions.

It is easy for a caller to make a mistake andfail to establish a precondition. It is also difficult for an implementer to cheaply, efficiently, andcompletely check preconditions. We would like to rely on the caller to get the preconditions right,but we need a way to test for correctness. For now, just note that some pre- and postconditions areeasy to check (e.g., len is positive and len∗wid is positive).

Others are semantic in nature and hardto test directly. For example, how do we test ‘‘the return value is the area of a rectangle with sideslen and wid’’? This is a semantic constraint because we have to know the meaning of ‘‘area of arectangle,’’ and just trying to multiply len and wid again with a precision that precluded overflowcould be costly.It seems that writing out the pre- and postconditions for area() uncovered a subtle problem withthis very simple function. This is not uncommon. Writing out pre- and postconditions is a greatdesign tool and provides good documentation. Mechanisms for documenting and enforcing conditions are discussed in §13.4.If a function depends only on its arguments, its preconditions are on its arguments only. However, we have to be careful about functions that depend on non-local values (e.g., a member function that depends on the state of its object).

In essence, we have to consider every nonlocal valueread as an implicit argument to a function. Similarly, the postcondition of a function without sideeffects simply states that a value is correctly computed, but if a function writes to nonlocal objects,its effect must be considered and documented.332FunctionsChapter 12The writer of a function has several alternatives, including:[1] Make sure that every input has a valid result (so that we don’t have a precondition).[2] Assume that the precondition holds (rely on the caller not to make mistakes).[3] Check that the precondition holds and throw an exception if it does not.[4] Check that the precondition holds and terminate the program if it does not.If a postconditon fails, there was either an unchecked precondition or a programming error.

§13.4discusses ways to represent alternative strategies for checking.12.5 Pointer to FunctionLike a (data) object, the code generated for a function body is placed in memory somewhere, so ithas an address. We can have a pointer to a function just as we can have a pointer to an object.However, for a variety of reasons – some related to machine architecture and others to systemdesign – a pointer to function does not allow the code to be modified. There are only two thingsone can do to a function: call it and take its address. The pointer obtained by taking the address ofa function can then be used to call the function. For example:void error(string s) { /* ... */ }void (∗efct)(string);// pointer to function taking a string argument and returning nothingvoid f(){efct = &error;efct("error");}// efct points to error// call error through efctThe compiler will discover that efct is a pointer and call the function pointed to.

That is, dereferencing a pointer to function using ∗ is optional. Similarly, using & to get the address of a functionis optional:void (∗f1)(string) = &error;void (∗f2)(string) = error;void g(){f1("Vasa");(∗f1)("Mary Rose");}// OK: same as = error// OK: same as = &error// OK: same as (*f1)("Vasa")// OK: as f1("Mary Rose")Pointers to functions have argument types declared just like the functions themselves.

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

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

Список файлов книги

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