Accelerated C++ 习题 第1章
文章目录
[1-2] 以下的定义有效吗?理由是什么?
const std::string exclam = "!";
const std::string message = "Hello" + ", world" + exclam;
[1-2]
第一行有效;
第二行无效,两个字符串常量不能直接用 + 操作符;字符串常量是 const char* 类型,它们没有+操作符;
所以+ 两边至少要有一个是string类型的
[1-3] 以下的定义有效吗?如果有效的话,它是做什么的?如果无效,为什么呢?
#include<iostream>
#include<string>
int main()
{
{
const std::string s = "a string";
std::cout << s << std::endl;
}
{
const std::string s = "another string";
std::cout << s << std::endl;
}
return 0;
}
[1-3] 有效 分别给花括号局部变量 s 赋值并输出。
[1-4] 下面的这个程序又怎样呢?如果我们把倒数第三行的 }} 改成 };} 的话,会出现什么情况呢?
#include<iostream>
#include<string>
int main()
{
{const std::string s = "a string";
std::cout << s << std::endl;
{const std::string s = "another string";
//std::cout << s << std::endl;}}
std::cout << s << std::endl;} ;}
return 0;
}
[1-4] 没有影响,内部作用域嵌套在外部作用域内,内部作用域的s隐藏了外部作用域的s,所以是有效的
[1-5] 下面这个程序呢?如果有效,它是做什么的?如果无效,说出理由,然后把它改写成有效的程序。
#include<iostream>
#include<string>
int main()
{
{
std::string s = "a string";
{
std::string x = s + ", really";
std::cout << s << std::endl;
}
std::cout << x << std::endl; // x is out of its scope here
}
return 0;
}
[1-5] 无效,x 是局部变量只在局部作用域内有作用,改为全局的就可以了
[1-6] 在下面的程序向你发出输入请求的时候,如果你输入了两个名字(例如,Samuel Beckett),它会怎么样处理呢?在运行程序之前先预测一下结果,然后上机测一下
#include<iostream>
#include<string>
int main()
{
std::cout << "What is your name? ";
std::string name;
std::cin >> name;
std::cout << "Hello, " << name
<< std::endl << "And what is yours? ";
std::cin >> name;
std::cout << "Hello, " << name
<< ";nice to meet you roo!" << std::endl;
return 0;
}
1-6 每一次处理,每次赋值name都会不一样