设为首页 加入收藏

TOP

C++ Primer Plus复习题及答案(一)
2018-05-21 15:48:12 】 浏览:411
Tags:Primer Plus 习题 答案

1. 对于下面的情况,应使用哪种存储方案? 

a. homer是函数的形参。 

b. secret变量由两个文件共享。 

c. topsecret变量由一个文件中的所有函数共享,但对于其他文件来说是隐藏的。 

d. beencalled记录包含它的函数被调用的次数。 

答: 

a.homer将自动成为自动变量。 

b.应该在一个文件中将secret定义为外部变量,并在第二个文件中使用extern来声明它。 

c.可以在外部定义前加上关键字static,将topsecret定义为一个有内部链接的静态变量。也可在一个未命名的名称空间中进行定义 

d.应在函数中的声明前加上关键字static,将beencalled定义为一个本地静态变量。

2. using声明和using编译指令之间有何区别? 

答:using声明使得名称空间中的单个名称可用,其作用域域using所在的声明区域相同。Using编译指令使名称空间中的所有名称可用。使用using编译指令时,就像在一个包含using声明和名称空间本身的最小声明区域中声明了这些名称一样。

3. 重新编写下面的代码,使其不使用using声明和using编译指令。

#include<iostream>

using namespace std;

int main()

{

    double x;

    cout<<”Enter value: ”;

    while(!(cin>>x))

    {

    cout<<”Bad input. Please enter a number: ”;

    cin.clear();

    while(cin.get() != ‘\n’)

        continue;

}

cout<<”Value = ”<<x<<endl;

return 0;

}

答:

#include<iostream>

int mian() {

    double x;

    std::cout << "Enter value: ";

    while (!(std::cin >> x)) {

        std::cout << "Bad input. Please enter a numeber: ";

        std::cin.clear();

        while (std::cin.get() != '\n')

            continue;

    }

    std::cout << "Value = " << x << std::endl;

    return 0;

}

4. 重新编写下面的代码,使之使用using声明,而不是using编译指令。

#include<iostream>

using namespace std;

int main() {

    double x;

    cout << "Enter calus: ";

    while (!(cin >> x)) {

        cout << "Bad input. Please enter a number: ";

        cin.clear();

        while (cin.get() != '\n')

            continue;

    }

    cout << "Value = " << x << endl;

    return 0;

}

答:

#include<iostream>

int main() {

    using std::cin;

    using std::cout;

    using std::endl;

    double x;

    cout << "Enter value: ";

    while (!(cin >> x)) {

        cout << "Bad input. Please enter a number: ";

        cin.clear();

        while (cin.get() != '\n')

            continue;

    }

    cout << "Value = " << x << endl;

    return 0;

}

5.在一个文件中调用average(3,6)函数时,它返回两个int参数的int平均值,在同一个程序的另一个文件中调用时,它返回两个int参数的double平均值。应如何实现? 

答:可以在每个文件中包含单独的静态函数定义。或者每个文件都在未命名的名称空间中定义一个合适的average()函数。

6.下面的程序由两个文件组成,该程序显示声明内容?

//file1.cpp

#include<iostream>

using namespace std;

void other();

void another();

int x = 10;

int y;

int main() {

    cout << x << endl;

    {

        int x = 4;

        cout << x << endl;

        cout << y << endl;

    }

    other();

    another();

 

首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇C++11 基于范围的for循环讲解 下一篇关于c++中与的容器(运算符的重载..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目