C++ Primer 第二章 变量初始化

Variable Definitions

A variable provides us with named storage that our programs can manipulate.

Each variable in C++ has a type.

Variable Definitions: A simple variable definition consists of a type specifier, followed by a list of one or more variable names separated by commas, and ends with a semicolon.

Initializers

An object that is initialized gets the specified value at the moment it is created.

// ok: price is defined and initialized before it is used to initialize discount
double price = 109.99, discount = price * 0.16;
// ok: call applyDiscount and use the return value to initialize salePrice
double salePrice = applyDiscount(price, discount);

Warning
Initialization is not assignment.
Initialization happens when a variable is given a value when it is created.

Assignment obliterates an object’s current value and replaces that value with a new one.

List Initialization

The language defines several different forms of initialization:

int units_sold = 0;
int units_sold = {0};
int units_sold{0};
int units_sold(0);

The generalized use of curly braces for initialization is referred to as list initialization.

The compiler will not let us list initialize variables of built-in type if
the initializer might lead to the loss of information:

long double ld = 3.1415926536;
int a{ld}, b = {ld}; // error: narrowing conversion required
int c(ld), d = ld; // ok: but value will be truncated

Default Initialization

When we define a variable without an initializer, the variable is default initialized.

The value of an object of built-in type that is not explicitly initialized depends on where it is defined.

Variables defined outside any function body are initialized to zero.

variables of built-in type defined inside a function are uninitialized.
It is an error to copy or otherwise try to access the value of a variable whose value is undefined.

Objects of class type that we do not explicitly initialize have a value that is defined by the class.

不同初始化方法:
Is there a difference between copy initialization and direct initialization?
Different forms of initialization
Initialization of variables
Initializers

发布了120 篇原创文章 · 获赞 2 · 访问量 5782

猜你喜欢

转载自blog.csdn.net/Lee567/article/details/104080849