第2章 變數和基本型別
Exercise 2.9
Explain the following definitions. For those that are illegal, explain what’s wrong and how to correct it.
-
(a)
std::cin >> int input_value;
-
(b)
int i = { 3.14 };
-
(c)
double salary = wage = 9999.99;
-
(d)
int i = 3.14;
(a): error: expected `(` for function-style cast or type construction.(?)
int input_value = 0;
std::cin >> input_value;
(b):when you compile the code without the argument “-std=c++11
“, you will get the warning below: warning: implicit conversion from `double` to `int` changes value from 3.14 to 3.
when you compile the code using “-std=c+11
“, you will get a error below: error: type `double` cannot be narrowed to `int` in initializer list
conclusion: Obviously, list initialization becomes strict in c++11.
double i = { 3.14 };
(c): –if you declared `wage` before, it`s right. Otherwise, you`ll get a error: error: use of undeclared identifier `wage`
double wage;
double salary = wage = 9999.99;
(d): ok: but value will be truncated(截斷).
double i = 3.14;
Exercise 2.10
What are the initial values, if any, of each of the following variables?
std::string global_str;
int global_int;
int main()
{
int local_int;
std::string local_str;
}
global_str
is global variable, so the value is empty string.
global_int
is global variable, so the value is zero.
local_int
is a local variable which is not uninitialized, so it has a undefined value.
local_str
is also a local variable which is not uninitialized, but it has a value that is defined by the class. So it is empty string.
PS: please read P44 in the English version, P40 in Chinese version to get more.
The note: Uninitialized objects of built-in type defined inside a function body have a undefined value. Objects of class type that we do not explicitly明確地) inititalize have a value that is defined by class.
定義於函式內部體內的內建型別的物件如果沒有初始化,則其值 未定義。
類的物件如果沒有顯式地初始化,則其值 由類決定。