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

const Stock & Stock::topval(const Stock & s) const

{

    if (s.total_val > total_val)

        return s;

    else

        return *this;

}

Of course, you want to see if the this pointer works, and a natural place to use the new method is in a program with an array of objects, which leads us to the next topic.

An Array of Objects

Often, as with the Stock examples, you want to create several objects of the same class. You can create separate object variables, as the examples have done so far in this chapter, but it might make more sense to create an array of objects. That might sound like a major leap into the unknown, but, in fact, you declare an array of objects the same way you declare an array of any of the standard types:

Stock mystuff[4]; // creates an array of 4 Stock objects

Recall that a program always calls the default class constructor when it creates class objects that aren’t explicitly initialized. This declaration requires either that the class explicitly define no constructors at all, in which case the implicit do-nothing default constructor is used, or, as in this case, that an explicit default constructor be defined. Each element—mystuff[0], mystuff[1], and so on—is a Stock object and thus can be used with the Stock methods:

mystuff[0].update();      // apply update() to 1st element

mystuff[3].show();        // apply show() to 4th element

const Stock * tops = mystuff[2].topval(mystuff[1]);

      // compare 3rd and 2nd elements and set tops

      // to point at the one with a higher total value

You can use a constructor to initialize the array elements. In that case, you have to call the constructor for each individual element:

const int STKS = 4;

Stock stocks[STKS] = {

    Stock("NanoSmart", 12.5, 20),

    Stock("Boffo Objects", 200, 2.0),

    Stock("Monolithic Obelisks", 130, 3.25),

    Stock("Fleep Enterprises", 60, 6.5)

    };

Here the code uses the standard form for initializing an array: a comma-separated list of values enclosed in braces. In this case, a call to the constructor method represents each value. If the class has more than one constructor, you can use different constructors for different elements:

const int STKS = 10;

Stock stocks[STKS] = {

    Stock("NanoSmart", 12.5, 20),

    Stock(),

    Stock("Monolithic Obelisks", 130, 3.25),

};

This initializes stocks[0] and stocks[2] using the Stock(const string & co, long n, double pr) constructor as well as stocks[1] using the Stock() constructor. Because this declaration only partially initializes the array, the remaining seven members are initialized using the default constructor.

Listing 10.9 applies these principles to a short program that initializes four array elements, displays their contents, and tests the elements to find the one with the highest total value. Because topval() examines just two objects at a time, the program uses a for loop to examine the whole array. Also it uses a pointer-to-Stock to keep track of which element has the highest value. This listing uses the Listing 10.7 header file and the Listing 10.8 methods file.

Listing 10.9. usestok2.cpp

// usestok2.cpp -- using the Stock class

// compile with stock20.cpp

#include

#include "stock20.h"

const int STKS = 4;

int main()

{

// create an array of initialized objects

    Stock stocks[STKS] = {

        Stock("NanoSmart", 12, 20.0),

        Stock("Boffo Objects", 200, 2.0),

        Stock("Monolithic Obelisks", 130, 3.25),

        Stock("Fleep Enterprises", 60, 6.5)

        };

    std::cout << "Stock holdings:\n";

    int st;

    for (st = 0; st < STKS; st++)

        stocks[st].show();

// set pointer to first element

    const Stock * top = &stocks[0];

    for (st = 1; st < STKS; st++)

        top = &top->topval(stocks[st]);

// now top points to the most valuable holding

    std::cout << "\nMost valuable holding:\n";

    top->show();

     return 0;

}

Here is the output from the program in Listing 10.9:

Stock holdings:

Company: NanoSmart  Shares: 12

  Share Price: $20.000  Total Worth: $240.00

Company: Boffo Objects  Shares: 200

  Share Price: $2.000  Total Worth: $400.00

Company: Monolithic Obelisks  Shares: 130

  Share Price: $3.250  Total Worth: $422.50

Company: Fleep Enterprises  Shares: 60

  Share Price: $6.500  Total Worth: $390.00

Most valuable holding:

Company: Monolithic Obelisks  Shares: 130

  Share Price: $3.250  Total Worth: $422.50

One thing to note about Listing 10.9 is that most of the work goes into designing the class. When that’s done, writing the program itself is rather simple.

Incidentally, knowing about the this pointer makes it easier to see how C++ works under the skin. For example, the original Unix implementation used a C++ front-end cfront that converted C++ programs to C programs. To handle method definitions, all it had to do is convert a C++ method definition like

void Stock::show() const

{

    cout << "Company: " << company

         << "  Shares: " << shares << '\n'

         << "  Share Price: $" << share_val

         << "  Total Worth: $" << total_val << '\n';

}

to the following C-style definition:

void show(const Stock * this)

{

    cout << "Company: " << this->company

         << "  Shares: " << this->shares << '\n'

         << "  Share Price: $" << this->share_val

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

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

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

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