C++ Primer 课后习题解析

发布时间:2019-08-06 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了C++ Primer 课后习题解析脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

第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.

定义于函数内部体内的内置类型的对象如果没有初始化,则其值 未定义

类的对象如果没有显式地初始化,则其值 由类决定

脚本宝典总结

以上是脚本宝典为你收集整理的C++ Primer 课后习题解析全部内容,希望文章能够帮你解决C++ Primer 课后习题解析所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。