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

Here, arp is the name of an array; hence, it is the address of its first element. But its first element is a pointer, so ppa has to be a pointer to a pointer to const antarctica_years_end, hence the **. There are several ways you could mess up this declaration. For example, you could omit the const, forget an * or two, transpose letters, or otherwise mangle the structure type. Here is an instance for which the C++11 version of auto is convenient. The compiler is perfectly aware of what type arp is, so it can deduce the correct type for you:

auto ppb = arp; // C++11 automatic type deduction

In the past, the compiler used its knowledge of the correct type to complain about errors you may have made in the declaration; now it can let its knowledge work for you.

How can you use ppa to access data? Because ppa is a pointer to a pointer to a structure, *ppa is a pointer to a structure, so you can use it with the indirect membership operator:

std::cout << (*ppa)->year << std::endl;

std::cout << (*(ppb+1))->year << std::endl;

Because ppa points to the first member of arp, *ppa is the first member, which is &s01. So (*ppa)->year is the year member of s01. In the second statement, ppb+1 points to the next element, arp[1], which is &s02. The parentheses are needed to get the correct associations. For example, *ppa->year would attempt to apply the * operator to ppa->year, which fails because the year member is not a pointer.

Is all this really true? Listing 4.23 incorporates all the preceding statements into a short program.

Listing 4.23. mixtypes.cpp

// mixtypes.cpp -- some type combinations

#include

struct antarctica_years_end

{

    int year;

 /* some really interesting data, etc. */

};

int main()

{

    antarctica_years_end s01, s02, s03;

    s01.year = 1998;

    antarctica_years_end * pa = &s02

    pa->year = 1999;

    antarctica_years_end trio[3]; // array of 3 structures

    trio[0].year = 2003;

    std::cout << trio->year << std::endl;

    const antarctica_years_end * arp[3] = {&s01, &s02, &s03};

    std::cout << arp[1]->year << std::endl;

    const antarctica_years_end ** ppa = arp;

    auto ppb = arp; // C++11 automatic type deduction

// or else  use const antarctica_years_end ** ppb = arp;

    std::cout << (*ppa)->year << std::endl;

    std::cout << (*(ppb+1))->year << std::endl;

    return 0;

}

Here’s the output:

2003

1999

1998

1999

The program compiles and works as promised.

Array Alternatives

Earlier this chapter mentioned the vector and array template classes as alternatives to the built-in array. Let’s take a brief look now at how they are used and at some of the benefits of using them.

The vector Template Class

The vector template class is similar to the string class in that it is a dynamic array. You can set the size of a vector object during runtime, and you can append new data to the end or insert new data in the middle. Basically, it’s an alternative to using new to create a dynamic array. Actually, the vector class does use new and delete to manage memory, but it does so automatically.

At this time we won’t venture very deeply into what it means to be a template class. Instead, we’ll look at a few basic practical matters. First, to use a vector object, you need to include the vector header file. Second, the vector identifier is part of the std namespace, so you can use a using directive, a using declaration, or std::vector. Third, templates use a different syntax to indicate the type of data stored. Fourth, the vector class uses a different syntax to indicate the number of elements. Here are some examples:

#include

...

using namespace std;

vector vi;        // create a zero-size array of int

int n;

cin >> n;

vector vd(n);  // create an array of n doubles

We say that vi is an object of type vector and that vd is an object of type vector. Because vector objects resize automatically when you insert or add values to them, it’s okay for vi to start with 0 size. But for the resizing to work, you would use the various methods that are part of the vector package.

In general, the following declaration creates a vector object vt that can hold n_elem elements of type typeName:

vector<typeName> vt(n_elem);

The parameter n_elem can be an integer constant or an integer variable.

The array Template Class (C++11)

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

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

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

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