The following statements define five variables:
- int units_sold;
- double sales_price, avg_price;
std::string title; Sales_item curr_book;
Each definition starts with a type specifier, followed by a comma-separated list of one or more names. A semicolon terminates the definition. The type specifier names the type associated with the object: int, double, std::string, and Sales_item are all names of types. The types int and double are built-in types, std::string is a type defined by the library, and Sales_item is a type that we used in Section 1.5 (p. 20) and will define in subsequent chapters. The type determines the amount of storage that is allocated for the variable and the set of operations that can be performed on it.
Multiple variables may be defined in a single statement:
- double salary, wage;
- int month,
- day, year;
- std::string address;
Initialization
A definition specifies a variable’s type and identifier. A definition may also provide an initial value for the object. An object defined with a specified first value is spoken of as initialized. C++(www.cppentry.com) supports two forms of variable initialization:
copy-initialization and direct-initialization. The copy-initialization syntax uses the equal (=) symbol; direct-initialization places the initializer in parentheses:
- int ival(1024);
- int ival = 1024;
In both cases, ival is initialized to 1024.
本书会反复提到拷贝初始化和直接初始化两个术语,值得印在脑中。另外,拷贝初始化不是赋值。
Although, at this point in the book, it may seem obscure to the reader, in C++(www.cppentry.com) it is essential to understand that initialization is not assignment. Initialization happens when a variable is created and gives that variable its initial value. Assignment involves obliterating an object’s current value and replacing that value with a new one.
Many new C++(www.cppentry.com) programmers are confused by the use of the = symbol to initialize a variable. It is tempting to think of initialization as a form of assignment. But initialization and assignment are different operations in C++(www.cppentry.com). This concept is particularly confusing because in many other languages the distinction is irrelevant and can be ignored. Moreover, even in C++(www.cppentry.com) the distinction rarelymatters until one attempts to write fairly complex classes. Nonetheless, it is a crucial concept and one that we will reiterate throughout the text.
There are subtle differences between copy- and direct-initialization when initializing objects of a class type. We won’t completely explain these differences until Chapter 13. For now, it’s worth knowing that the direct syntax is more flexible and can be slightly more efficient.