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

const double & rx

The non-const lvalue reference matches the lvalue argument w. The other two arguments are rvalues, and the const lvalue reference can refer to copies of them.

b.

double & rx

double && rx

double && rx

The lvalue reference matches the lvalue argument w, and the rvalue references matches the two rvalue arguments.

c.

const double & rx

double && rx

double && rx

The const lvalue reference matches the lvalue argument w, and the rvalue reference matches the two rvalues.

In short, a non-const lvalue parameter matches an lvalue argument, a non-const rvalue parameter matches an rvalue argument, and a const lvalue parameter can match either an lvalue or an rvalue argument, but the compiler will prefer the first two choices, if available.

4. They are the default constructor, the copy constructor, the move constructor, the destructor, the copy assignment operator, and the move assignment operator. They are special because the compiler can automatically provide defaulted versions of these functions, depending on the context.

5. A move constructor can be used when it makes sense to transfer ownership of data instead of copying it, but there is no mechanism for transferring ownership of a standard array. If the Fizzle class used a pointer and dynamic memory allocation, then one can transfer ownership by reassigning the address of the data to a new pointer.

6.

#include

#include

template

  void show2(double x, T fp) {std::cout << x << " -> " << fp(x) << '\n';}

int main()

{

    show2(18.0, [](double x){return 1.8*x + 32;});

    return 0;

}

7.

#include

#include

#include

const int Size = 5;

template

  void sum(std::array a, T& fp);

int main()

{

    double total = 0.0;

    std::array temp_c = {32.1, 34.3, 37.8, 35.2, 34.7};

    sum(temp_c, [&total](double w){total += w;});

    std::cout << "total: " << total << '\n';

    std::cin.get();

    return 0;

}

template

  void sum(std::array a, T& fp)

{

    for(auto pt = a.begin(); pt != a.end(); ++pt)

    {

        fp(*pt);

    }

}

Index

Symbols

<=, 217

+ (addition operator), overloading, 569–572

-= (assignment operator), 212

*= (assignment operator), 212

+= (assignment operator), 211

%= (assignment operator), 212

/= (assignment operator), 212

= (assignment operator), 43–44, 644, 767–768, 772–775

compared to equality operator, 218–220

custom definitions, 645–646

enumerator values, setting, 152

overloading, 652–658

sayings1.cpp, 656

string1.cpp, 653–656

string1.h, 652–653

potential problems, 645

strings, 133–134

structures, 145–146

when to use, 644

& (bitwise AND operator), 1239–1240

~ (bitwise negation operator), 1237

| (bitwise OR operator), 1237–1238

^ (bitwise XOR operator), 1238

{} (braces), 258

[] (brackets), 649–651

, (comma operator), 214–217

example, 214–216

precedence, 217

/*...*/ comment notation, 33

// comment notation, 27, 32

+ (concatenation operator), strings, 133–134

?: (conditional operator), 273–274

- - (decrement operator), 207–208

pointers, 210–211

postfixing, 209–210

prefixing, 209–210

* (dereferencing operator), 155–159

pointers, 171–172

/ (division operator), 100–101

== (equality operator), 217

compared to assignment operator, 218–220

++ (increment operator), 197, 207–208

pointers, 210–211

postfixing, 209–210

prefixing, 209–210

!= (inequality operator), 217

&& (logical AND operator), 262

alternative representations, 270

example, 263–265

precedence, 269–270

ranges, 265–267

! (logical NOT operator), 267–269

alternative representations, 270

precedence, 269

|| (logical OR operator), 260–262

alternative representations, 270

example, 261–262

-]* (member dereferencing operator), 1243–1246

.* (member dereferencing operator), 1243–1246

% (modulus operator), 101–102

* (multiplication operator), overloading, 574–578

\n newline character, 38–39

< operator, 217

. (period), 255

# (pound sign), 234

“ (quotation marks), 36

& (reference operator), 383–386

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

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

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

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