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

    cout << " and " << pal.name << "!\n";

// pal.name is the name member of the pal variable

    cout << "You can have both for $";

    cout << guest.price + pal.price << "!\n";

    return 0;

}

Here is the output from the program in Listing 4.11:

Expand your guest list with Glorious Gloria and Audacious Arthur!

You can have both for $62.98!

Program Notes

One important matter related to the program in Listing 4.11 is where to place the structure declaration. There are two choices for structur.cpp. You could place the declaration inside the main() function, just after the opening brace. The second choice, and the one made here, is to place it outside and preceding main(). When a declaration occurs outside any function, it’s called an external declaration. For this program, there is no practical difference between the two choices. But for programs consisting of two or more functions, the difference can be crucial. The external declaration can be used by all the functions following it, whereas the internal declaration can be used only by the function in which the declaration is found. Most often, you want an external structure declaration so that all the functions can use structures of that type (see Figure 4.7).

Figure 4.7. Local and external structure declarations.

Variables, too, can be defined internally or externally, with external variables shared among functions. (Chapter 9, “Memory Models and Namespaces,” looks further into that topic.) C++ practices discourage the use of external variables but encourage the use of external structure declarations. Also it often makes sense to declare symbolic constants externally.

Next, notice the initialization procedure:

inflatable guest =

{

    "Glorious Gloria",  // name value

    1.88,               // volume value

    29.99               // price value

};

As with arrays, you use a comma-separated list of values enclosed in a pair of braces. The program places one value per line, but you can place them all on the same line. Just remember to separate items with commas:

inflatable duck = {"Daphne", 0.12, 9.98};

You can initialize each member of the structure to the appropriate kind of data. For example, the name member is a character array, so you can initialize it to a string.

Each structure member is treated as a variable of that type. Thus, pal.price is a double variable, and pal.name is an array of char. And when the program uses cout to display pal.name, it displays the member as a string. By the way, because pal.name is a character array, we can use subscripts to access individual characters in the array. For example, pal.name[0] is the character A. But pal[0] is meaningless because pal is a structure, not an array.

C++11 Structure Initialization

As with arrays, C++11 extends the features of list-initialization. The = sign is optional:

inflatable duck {"Daphne", 0.12, 9.98};  // can omit the = in C++11

Next, empty braces result in the individual members being set to 0. For example, the following declaration results in mayor.volume and mayor.price being set to 0 and all the bytes in mayor.name being set to 0:

inflatable mayor {};

Finally, narrowing is not allowed.

Can a Structure Use a string Class Member?

Can you use a string class object instead of a character array for the name member? That is, can you declare a structure like this:

#include

struct inflatable   // structure definition

{

    std::string name;

    float volume;

    double price;

};

The answer is yes unless you are using an obsolete compiler that does not support initialization of structures with string class members.

Make sure that the structure definition has access to the std namespace. You can do this by moving the using directive so that it is above the structure definition. The better choice, as shown previously, is to declare name as having type std::string.

Other Structure Properties

C++ makes user-defined types as similar as possible to built-in types. For example, you can pass structures as arguments to a function, and you can have a function use a structure as a return value. Also you can use the assignment operator (=) to assign one structure to another of the same type. Doing so causes each member of one structure to be set to the value of the corresponding member in the other structure, even if the member is an array. This kind of assignment is called memberwise assignment. We’ll defer passing and returning structures until we discuss functions in Chapter 7, “Functions: C++’s Programming Modules,” but we can take a quick look at structure assignment now. Listing 4.12 provides an example.

Listing 4.12. assgn_st.cpp

// assgn_st.cpp -- assigning structures

#include

struct inflatable

{

    char name[20];

    float volume;

    double price;

};

int main()

{

    using namespace std;

    inflatable bouquet =

    {

        "sunflowers",

        0.20,

        12.49

    };

    inflatable choice;

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

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

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

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