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

    hours += minutes / 60;

    minutes %= 60;

}

void Time::AddHr(int h)

{

    hours += h;

}

void Time::Reset(int h, int m)

{

    hours = h;

    minutes = m;

}

Time Time::operator+(const Time & t) const

{

    Time sum;

    sum.minutes = minutes + t.minutes;

    sum.hours = hours + t.hours + sum.minutes / 60;

    sum.minutes %= 60;

    return sum;

}

Time Time::operator-(const Time & t) const

{

    Time diff;

    int tot1, tot2;

    tot1 = t.minutes + 60 * t.hours;

    tot2 = minutes + 60 * hours;

    diff.minutes = (tot2 - tot1) % 60;

    diff.hours = (tot2 - tot1) / 60;

    return diff;

}

Time Time::operator*(double mult) const

{

    Time result;

    long totalminutes = hours * mult * 60 + minutes * mult;

    result.hours = totalminutes / 60;

    result.minutes = totalminutes % 60;

    return result;

}

std::ostream & operator<<(std::ostream & os, const Time & t)

{

    os << t.hours << " hours, " << t.minutes << " minutes";

    return os;

}

Listing 11.12 shows a sample program. Technically, usetime3.cpp doesn’t have to include iostream because mytime3.h already includes that file. However, as a user of the Time class, you don’t necessarily know which files are included in the class code, so you would take the responsibility of declaring those header files that you know your part of the code needs.

Listing 11.12. usetime3.cpp

//usetime3.cpp -- using the fourth draft of the Time class

// compile usetime3.cpp and mytime3.cpp together

#include

#include "mytime3.h"

int main()

{

   using std::cout;

   using std::endl;

   Time aida(3, 35);

   Time tosca(2, 48);

   Time temp;

   cout << "Aida and Tosca:\n";

   cout << aida<<"; " << tosca << endl;

   temp = aida + tosca;     // operator+()

   cout << "Aida + Tosca: " << temp << endl;

   temp = aida* 1.17;  // member operator*()

   cout << "Aida * 1.17: " << temp << endl;

   cout << "10.0 * Tosca: " << 10.0 * tosca << endl;

   return 0;

}

Here is the output of the program in Listings 11.10, 11.11, and 11.12:

Aida and Tosca:

3 hours, 35 minutes; 2 hours, 48 minutes

Aida + Tosca: 6 hours, 23 minutes

Aida * 1.17: 4 hours, 11 minutes

10.0 * Tosca: 28 hours, 0 minutes

Overloaded Operators: Member Versus Nonmember Functions

For many operators, you have a choice between using member functions or nonmember functions to implement operator overloading. Typically, the nonmember version is a friend function so that it can directly access the private data for a class. For example, consider the addition operator for the Time class. It has this prototype in the Time class declaration:

Time operator+(const Time & t) const; // member version

Instead, the class could use the following prototype:

// nonmember version

friend Time operator+(const Time & t1, const Time & t2);

The addition operator requires two operands. For the member function version, one is passed implicitly via the this pointer and the second is passed explicitly as a function argument. For the friend version, both are passed as arguments.

Note

A nonmember version of an overloaded operator function requires as many formal parameters as the operator has operands. A member version of the same operator requires one fewer parameter because one operand is passed implicitly as the invoking object.

Either of these two prototypes matches the expression T2 + T3, where T2 and T3 are type Time objects. That is, the compiler can convert the statement

T1 = T2 + T3;

to either of the following:

T1 = T2.operator+(T3);    // member function

T1 = operator+(T2, T3);   // nonmember function

Keep in mind that you must choose one or the other form when defining a given operator, but not both. Because both forms match the same expression, defining both forms is an ambiguity error, leading to a compilation error.

Which form, then, is it best to use? For some operators, as mentioned earlier, the member function is the only valid choice. Otherwise, it often doesn’t make much difference. Sometimes, depending on the class design, the nonmember version may have an advantage, particularly if you have defined type conversions for the class. The section “Conversions and Friends,” near the end of this chapter, discusses this situation further.

More Overloading: A Vector Class

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

Все книги серии 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.

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

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