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

More Overloaded Operators

Some other operations make sense for the Time class. For example, you might want to subtract one time from another or multiply a time by a factor. This suggests overloading the subtraction and multiplication operators. The technique is the same as for the addition operator: you create operator-() and operator*() methods. That is, you add the following prototypes to the class declaration:

Time operator-(const Time & t) const;

Time operator*(double n) const;

Listing 11.7 shows the new header file.

Listing 11.7. mytime2.h

// mytime2.h -- Time class after operator overloading

#ifndef MYTIME2_H_

#define MYTIME2_H_

class Time

{

private:

    int hours;

    int minutes;

public:

    Time();

    Time(int h, int m = 0);

    void AddMin(int m);

    void AddHr(int h);

    void Reset(int h = 0, int m = 0);

    Time operator+(const Time & t) const;

    Time operator-(const Time & t) const;

    Time operator*(double n) const;

    void Show() const;

};

#endif

Then you add definitions for the new methods to the implementation file, as shown in Listing 11.8.

Listing 11.8. mytime2.cpp

// mytime2.cpp  -- implementing Time methods

#include

#include "mytime2.h"

Time::Time()

{

    hours = minutes = 0;

}

Time::Time(int h, int m )

{

    hours = h;

    minutes = m;

}

void Time::AddMin(int m)

{

    minutes += m;

    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;

}

void Time::Show() const

{

    std::cout << hours << " hours, " << minutes << " minutes";

}

With these changes made, you can test the new definitions with the code shown in Listing 11.9.

Listing 11.9. usetime2.cpp

// usetime2.cpp -- using the third draft of the Time class

// compile usetime2.cpp and mytime2.cpp together

#include

#include "mytime2.h"

int main()

{

    using std::cout;

    using std::endl;

    Time weeding(4, 35);

    Time waxing(2, 47);

    Time total;

    Time diff;

    Time adjusted;

    cout << "weeding time = ";

    weeding.Show();

    cout << endl;

    cout << "waxing time = ";

    waxing.Show();

    cout << endl;

    cout << "total work time = ";

    total = weeding + waxing;   // use operator+()

    total.Show();

    cout << endl;

    diff = weeding - waxing;    // use operator-()

    cout << "weeding time - waxing time = ";

    diff.Show();

    cout << endl;

    adjusted = total * 1.5;      // use operator+()

    cout << "adjusted work time = ";

    adjusted.Show();

    cout << endl;

    return 0;

}

Here is the output of the program in Listings 11.7, 11.8, and 11.9:

weeding time = 4 hours, 35 minutes

waxing time = 2 hours, 47 minutes

total work time = 7 hours, 22 minutes

weeding time - waxing time = 1 hours, 48 minutes

adjusted work time = 11 hours, 3 minutes

Introducing Friends

As you’ve seen, C++ controls access to the private portions of a class object. Usually, public class methods serve as the only access, but sometimes this restriction is too rigid to fit particular programming problems. In such cases, C++ provides another form of access: the friend. Friends come in three varieties:

• Friend functions

• Friend classes

• Friend member functions

By making a function a friend to a class, you allow the function the same access privileges that a member function of the class has. We’ll look into friend functions now, leaving the other two varieties to Chapter 15, “Friends, Exceptions, and More.”

Before seeing how to make friends, let’s look into why they might be needed. Often, overloading a binary operator (that is, an operator with two arguments) for a class generates a need for friends. Multiplying a Time object by a real number provides just such a situation, so let’s study that case.

In the previous Time class example, the overloaded multiplication operator is different from the other two overloaded operators in that it combines two different types. That is, the addition and subtraction operators each combine two Time values, but the multiplication operator combines a Time value with a double value. This restricts how the operator can be used. Remember, the left operand is the invoking object. That is,

A = B * 2.75;

translates to the following member function call:

A = B.operator*(2.75);

But what about the following statement?

A = 2.75 * B;     // cannot correspond to a member function

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

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

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

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