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

The Time class provides methods for adjusting and resetting times, for displaying time values, and for adding two times. Listing 11.2 shows the methods definitions; note how the AddMin() and Sum() methods use integer division and the modulus operator to adjust the minutes and hours values when the total number of minutes exceeds 59. Also because the only iostream feature used is cout and because it is used only once, it seems economical to use std::cout rather than use the whole std namespace.

Listing 11.2. mytime0.cpp

// mytime0.cpp  -- implementing Time methods

#include

#include "mytime0.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::Sum(const Time & t) const

{

    Time sum;

    sum.minutes = minutes + t.minutes;

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

    sum.minutes %= 60;

    return sum;

}

void Time::Show() const

{

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

}

Consider the code for the Sum() function. Note that the argument is a reference but that the return type is not a reference. The reason for making the argument a reference is efficiency. The code would produce the same results if the Time object were passed by value, but it’s usually faster and more memory-efficient to just pass a reference.

However, the return value cannot be a reference. The reason is that the function creates a new Time object (sum) that represents the sum of the other two Time objects. Returning the object, as this code does, creates a copy of the object that the calling function can use. If the return type were Time &, however, the reference would be to the sum object. But the sum object is a local variable and is destroyed when the function terminates, so the reference would be a reference to a non-existent object. Using a Time return type, however, means the program constructs a copy of sum before destroying it, and the calling function gets the copy.

Caution

Don’t return a reference to a local variable or another temporary object. When the function terminates and the local variable or temporary object disappears, the reference becomes a reference to non-existent data.

Finally, Listing 11.3 tests the time summation part of the Time class.

Listing 11.3. usetime0.cpp

// usetime0.cpp -- using the first draft of the Time class

// compile usetime0.cpp and mytime0.cpp together

#include

#include "mytime0.h"

int main()

{

    using std::cout;

    using std::endl;

    Time planning;

    Time coding(2, 40);

    Time fixing(5, 55);

    Time total;

    cout << "planning time = ";

    planning.Show();

    cout << endl;

    cout << "coding time = ";

    coding.Show();

    cout << endl;

    cout << "fixing time = ";

    fixing.Show();

    cout << endl;

    total = coding.Sum(fixing);

    cout << "coding.Sum(fixing) = ";

    total.Show();

    cout << endl;

    return 0;

}

Here is the output of the program in Listings 11.1, 11.2, and 11.3:

planning time = 0 hours, 0 minutes

coding time = 2 hours, 40 minutes

fixing time = 5 hours, 55 minutes

coding.Sum(fixing) = 8 hours, 35 minutes

Adding an Addition Operator

It’s a simple matter to convert the Time class to using an overloaded addition operator. You just change the name of Sum() to the odder-looking name operator+(). That’s right: You just append the operator symbol (+, in this case) to the end of operator and use the result as a method name. This is one place where you can use a character other than a letter, a digit, or an underscore in an identifier name. Listings 11.4 and 11.5 reflect this small change.

Listing 11.4. mytime1.h

// mytime1.h -- Time class before operator overloading

#ifndef MYTIME1_H_

#define MYTIME1_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;

    void Show() const;

};

#endif

Listing 11.5. mytime1.cpp

// mytime1.cpp  -- implementing Time methods

#include

#include "mytime1.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;

}

void Time::Show() const

{

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

}

Like Sum(), operator+() is invoked by a Time object, takes a second Time object as an argument, and returns a Time object. Thus, you can invoke the operator+() method by using the same syntax that Sum() uses:

total = coding.operator+(fixing);    // function notation

But naming the method operator+() also lets you use operator notation:

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

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

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

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