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

It has the fatal flaw of returning a reference to a variable declared locally inside version3(). This function compiles (with a warning), but the program crashes when attempting to execute the function. Specifically, the following assignment aspect causes the problem:

result = version3(input, "@@@");

The program attempts to refer to memory that is no longer in use.

Another Object Lesson: Objects, Inheritance, and References

The ostream and ofstream classes bring an interesting property of references to the fore. As you may recall from Chapter 6, “Branching Statements and Logical Operators,” objects of the ofstream type can use ostream methods, allowing file input/output to use the same forms as console input/output. The language feature that makes it possible to pass features from one class to another is called inheritance, and Chapter 13, “Class Inheritance,” discusses this feature in detail. In brief, ostream is termed a base class (because the ofstream class is based on it) and ofstream is termed a derived class (because it is derived from ostream). A derived class inherits the base class methods, which means that an ofstream object can use base class features such as the precision() and setf() formatting methods.

Another aspect of inheritance is that a base class reference can refer to a derived class object without requiring a type cast. The practical upshot of this is that you can define a function having a base class reference parameter, and that function can be used with base class objects and also with derived objects. For example, a function with a type ostream & parameter can accept an ostream object, such as cout, or an ofstream object, such as you might declare, equally well.

Listing 8.8 demonstrates this point by using the same function to write data to a file and to display the data onscreen; only the function call argument is changed. This program solicits the focal length of a telescope objective (its main mirror or lens) and of some eyepieces. Then it calculates and displays the magnification each eyepiece would produce in that telescope. The magnification equals the focal length of the telescope divided by the focal length of the eyepiece used, so the calculation is simple. The program also uses some formatting methods, which, as promised, work equally well with cout and with ofstream objects (fout, in this example).

Listing 8.8. filefunc.cpp

//filefunc.cpp -- function with ostream & parameter

#include

#include

#include

using namespace std;

void file_it(ostream & os, double fo, const double fe[],int n);

const int LIMIT = 5;

int main()

{

    ofstream fout;

    const char * fn = "ep-data.txt";

    fout.open(fn);

    if (!fout.is_open())

    {

        cout << "Can't open " << fn << ". Bye.\n";

        exit(EXIT_FAILURE);

    }

    double objective;

    cout << "Enter the focal length of your "

            "telescope objective in mm: ";

    cin >> objective;

    double eps[LIMIT];

    cout << "Enter the focal lengths, in mm, of " << LIMIT

         << " eyepieces:\n";

    for (int i = 0; i < LIMIT; i++)

    {

        cout << "Eyepiece #" << i + 1 << ": ";

        cin >> eps[i];

    }

    file_it(fout, objective, eps, LIMIT);

    file_it(cout, objective, eps, LIMIT);

    cout << "Done\n";

    return 0;

}

void file_it(ostream & os, double fo, const double fe[],int n)

{

    ios_base::fmtflags initial;

    initial = os.setf(ios_base::fixed); // save initial formatting state

    os.precision(0);

    os << "Focal length of objective: " << fo << " mm\n";

    os.setf(ios::showpoint);

    os.precision(1);

    os.width(12);

    os << "f.l. eyepiece";

    os.width(15);

    os << "magnification" << endl;

    for (int i = 0; i < n; i++)

    {

        os.width(12);

        os << fe[i];

        os.width(15);

        os << int (fo/fe[i] + 0.5) << endl;

    }

    os.setf(initial);   // restore initial formatting state

}

Here is a sample run of the program in Listing 8.8:

Enter the focal length of your telescope objective in mm: 1800

Enter the focal lengths, in mm, of 5 eyepieces:

Eyepiece #1: 30

Eyepiece #2: 19

Eyepiece #3: 14

Eyepiece #4: 8.8

Eyepiece #5: 7.5

Focal length of objective: 1800 mm

f.l. eyepiece  magnification

        30.0             60

        19.0             95

        14.0            129

         8.8            205

         7.5            240

Done

The following line writes the eyepiece data to the file ep-data.txt:

file_it(fout, objective, eps, LIMIT);

And this line writes the identical information in the identical format to the screen:

file_it(cout, objective, eps, LIMIT);

Program Notes

The main point of Listing 8.8 is that the os parameter, which is type ostream &, can refer to an ostream object such as cout and to an ofstream object such as fout. But the program also illustrates how ostream formatting methods can be used for both types. Let’s review, or, in some cases, examine for the first time, some of these methods. (Chapter 17, “Input, Output, and Files,” provides a fuller discussion.)

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

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

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

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

Все жанры