Читаем C++ Primer Plus полностью

Which prototype does the print() call match here? It doesn’t match any of them! A lack of a matching prototype doesn’t automatically rule out using one of the functions because C++ will try to use standard type conversions to force a match. If, say, the only print() prototype were #2, the function call print(year, 6) would convert the year value to type double. But in the earlier code there are three prototypes that take a number as the first argument, providing three different choices for converting year. Faced with this ambiguous situation, C++ rejects the function call as an error.

Some signatures that appear to be different from each other nonetheless can’t coexist. For example, consider these two prototypes:

double cube(double x);

double cube(double & x);

You might think this is a place you could use function overloading because the function signatures appear to be different. But consider things from the compiler’s standpoint. Suppose you have code like this:

cout << cube(x);

The x argument matches both the double x prototype and the double &x prototype. The compiler has no way of knowing which function to use. Therefore, to avoid such confusion, when it checks function signatures, the compiler considers a reference to a type and the type itself to be the same signature.

The function-matching process does discriminate between const and non-const variables. Consider the following prototypes:

void dribble(char * bits);          // overloaded

void dribble (const char *cbits);   // overloaded

void dabble(char * bits);           // not overloaded

void drivel(const char * bits);     // not overloaded

Here’s what various function calls would match:

const char p1[20] = "How's the weather?";

char p2[20] = "How's business?";

dribble(p1);      // dribble(const char *);

dribble(p2);      // dribble(char *);

dabble(p1);       // no match

dabble(p2);       // dabble(char *);

drivel(p1);       // drivel(const char *);

drivel(p2);       // drivel(const char *);

The dribble() function has two prototypes—one for const pointers and one for regular pointers—and the compiler selects one or the other, depending on whether the actual argument is const. The dabble() function only matches a call with a non-const argument, but the drivel() function matches calls with either const or non-const arguments. The reason for this difference in behavior between drivel() and dabble() is that it’s valid to assign a non-const value to a const variable, but not vice versa.

Keep in mind that the signature, not the function type, enables function overloading. For example, the following two declarations are incompatible:

long gronk(int n, float m);      // same signatures,

double gronk(int n, float m);    // hence not allowed

Therefore, C++ doesn’t permit you to overload gronk() in this fashion. You can have different return types, but only if the signatures are also different:

long gronk(int n, float m);        // different signatures,

double gronk(float n, float m);    // hence allowed

After we discuss templates later in this chapter, we’ll further discuss function matching.

Overloading Reference Parameters

Class designs and the STL often use reference parameters, and it’s useful to know how overloading works with different reference types. Consider the following three prototypes:

void sink(double & r1);       // matches modifiable lvalue

void sank(const double & r2); // matches modifiable or const lvalue, rvalue

void sunk(double && r3);      // matches rvalue

The lvalue reference parameter r1 matches a modifiable lvalue argument, such as a double variable. The const lvalue reference parameter r2 matches a modifiable lvalue argument, a const lvalue argument, and an rvalue argument, such as the sum of two double values. Finally, the rvalue reference r3 matches an rvalue. Note how r2 can match the same sort of arguments that r1 and r3 match. This raises the question of what happens when you overload a function on these three types of parameters. The answer is that the more exact match is made:

void staff(double & rs);         // matches modifiable lvalue

voit staff(const double & rcs);  // matches rvalue, const lvalue

void stove(double & r1);         // matches modifiable lvalue

void stove(const double & r2);   // matches const lvalue

void stove(double && r3);        // matches rvalue

This allows you to customize the behavior of a function based on the lvalue, const, or rvalue nature of the argument:

double x = 55.5;

const double y = 32.0;

stove(x);             // calls stove(double &)

stove(y);             // calls stove(const double &)

stove(x+y);           // calls stove(double &&)

If, say, you omit the stove(double &&) function, then stove(x+y) will call the stove(const double &) function instead.

An Overloading Example

Перейти на страницу:

Все книги серии Developer's Library

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных

Похожие книги

1С: Бухгалтерия 8 с нуля
1С: Бухгалтерия 8 с нуля

Книга содержит полное описание приемов и методов работы с программой 1С:Бухгалтерия 8. Рассматривается автоматизация всех основных участков бухгалтерии: учет наличных и безналичных денежных средств, основных средств и НМА, прихода и расхода товарно-материальных ценностей, зарплаты, производства. Описано, как вводить исходные данные, заполнять справочники и каталоги, работать с первичными документами, проводить их по учету, формировать разнообразные отчеты, выводить данные на печать, настраивать программу и использовать ее сервисные функции. Каждый урок содержит подробное описание рассматриваемой темы с детальным разбором и иллюстрированием всех этапов.Для широкого круга пользователей.

Алексей Анатольевич Гладкий

Программирование, программы, базы данных / Программное обеспечение / Бухучет и аудит / Финансы и бизнес / Книги по IT / Словари и Энциклопедии
1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

Алексей Анатольевич Гладкий

Финансы / Программирование, программы, базы данных