Accelerated C++ 习题 第1章

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都会不一样

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值