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

Listing 7.14. topfive.cpp

// topfive.cpp -- handling an array of string objects

#include

#include

using namespace std;

const int SIZE = 5;

void display(const string sa[], int n);

int main()

{

    string list[SIZE];     // an array holding 5 string object

    cout << "Enter your " << SIZE << " favorite astronomical sights:\n";

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

    {

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

        getline(cin,list[i]);

    }

    cout << "Your list:\n";

    display(list, SIZE);

    return 0;

}

void display(const string sa[], int n)

{

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

        cout << i + 1 << ": " << sa[i] << endl;

}

Here’s a sample run of the program in Listing 7.14:

Enter your 5 favorite astronomical sights:

1: Orion Nebula

2: M13

3: Saturn

4: Jupiter

5: Moon

Your list:

1: Orion Nebula

2: M13

3: Saturn

4: Jupiter

5: Moon

The main point to note in this example is that, aside from the getline() function, this program treats string just as it would treat any of the built-in types, such as int. If you want an array of string, you just use the usual array-declaration format:

string list[SIZE];     // an array holding 5 string object

Each element of the list array, then, is a string object and can be used as such:

getline(cin,list[i]);

Similarly, the formal argument sa is a pointer to a string object, so sa[i] is a string object and can be used accordingly:

cout << i + 1 << ": " << sa[i] << endl;

Functions and array Objects

Class objects in C++ are based on structures, so some of the same programming considerations that apply to structures also apply to classes. For example, you can pass an object by value to a function, in which case the function acts on a copy of the original object. Alternatively, you can pass a pointer to an object, which allows the function to act on the original object. Let’s look at an example using the C++11 array template class.

Suppose we have an array object intended to hold expense figures for each of the four seasons of the year:

std::array expenses;

(Recall that using the array class requires the array header file and that the name array is part of the std namespace.) If we want a function to display the contents of expenses, we can pass expenses by value:

show(expenses);

But if we want a function that modifies the expenses object, we need to pass the address of the object to the function:

fill(&expenses);

(The next chapter discusses an alternative approach, using references.) This is the same approach that Listing 7.13 used for structures.

How can we declare these two functions? The type of expenses is array, so that’s what must appear in the prototypes:

void show(std::array da);   // da an object

void fill(std::array * pa); // pa a pointer to an object

These considerations form the core of the sample program. The program adds a few more features. First, it replaces 4 with a symbolic constant:

const int Seasons = 4;

Second, it adds a const array object containing four string objects representing the four seasons:

const std::array Snames =

    {"Spring", "Summer", "Fall", "Winter"};

Note that the array template is not limited to holding the basic data types; it can use class types too. Listing 7.15 presents the program in full.

Listing 7.15. arrobj.cpp

//arrobj.cpp -- functions with array objects (C++11)

#include

#include

#include

// constant data

const int Seasons = 4;

const std::array Snames =

    {"Spring", "Summer", "Fall", "Winter"};

// function to modify array object

void fill(std::array * pa);

// function that uses array object without modifying it

void show(std::array da);

int main()

{

    std::array expenses;

    fill(&expenses);

    show(expenses);

    return 0;

}

void fill(std::array * pa)

{

    using namespace std;

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

    {

        cout << "Enter " << Snames[i] << " expenses: ";

        cin >> (*pa)[i];

    }

}

void show(std::array da)

{

    using namespace std;

    double total = 0.0;

    cout << "\nEXPENSES\n";

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

    {

        cout << Snames[i] << ": $" << da[i] << endl;

        total += da[i];

    }

    cout << "Total Expenses: $" << total << endl;

}

Here’s a sample run:

Enter Spring expenses: 212

Enter Summer expenses: 256

Enter Fall expenses: 208

Enter Winter expenses: 244

EXPENSES

Spring: $212

Summer: $256

Fall: $208

Winter: $244

Total: $920

Program Notes

Because the const array object Snames is declared above all the functions, it can be used in any of the following function definitions. Like the const Seasons, Snames is shared by the whole source code file. The program doesn’t have a using directive, so array and string have to be used with the str:: qualifier. To keep the program short and focused on how functions can use objects, the fill() function doesn’t check for valid input.

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

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

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

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