C++ 基础练习 - Chapter 12 (基础练习 完结版)

Review Questions

12.1 What is generic Programming? How is it implemented in C++?

Answer:

Generic programming is an approach where generic types are used as parameters in algorithms so that they work for variety of suitable data types and data structures.

It is implemented in C++ using class templates.

12.2 A template can be considered as a kind of macro. Then what is the difference between them?

Answer:

Templates are a feature of the C++ programming language at allows a functions or class to work on many different data types without being written for each one. Templates are of great utility programmers in C++, especially when combined with multiple inheritance and operator overloading. The C++ STL provides many usefu functions within a framework of connected templates.

On the other hand the # define directive is typically used to associate meaningful identifiers with constants, keywords and commonly used statements or expressions. Identifiers that represent constants are sometimes called “symbolic constant” or “manifest constant”.

Identifiers that represents statements or expressions are called “macro”. In this preprocessor documentation only the term “macro” is used.

12.3 Distinguish between overloaded functions and junction templates.

Answer:

Basic difference is function body will not differ in function overloading.

12.4 Distinguish between the terms class template and template class.

Answer:

Class template is a generic class. The class template definition is very similar to an ordinary class definition except the prefix template and the use of type T.

On the other hand a class created from a class template is called a template class. The process of creating a specific class from a class template is called instantiation.

12.5 A class (or function) template is known as a parameterized class (or function). Comment.

Answer:

When an object of specific type is defined for actual use, the template definition for that class is substituted with the required data type. Since a template is defined with a parameter that would be replaced by a specified data type at the time of actual use of the class or function, the templates are called parameterized classes or functions.

12.6 What is an exception?

Answer:

Exceptions are run-time anomalies or unusual conditions that a program may encounter while executing.

12.7 How is an exception handled in C++?

Answer:

C++ exception handling mechanism is basically built upon the three keywords, namely, try, throw and catch. The keyword try is used to preface a block of statements which may generate exceptions. This block is known as try block. When an exception is detected, it is thrown using throw statement in the try block. A catch block defined by the keyword “catch” catches the exception thrown statement in the try block and handles it appropriately. This relationship is shown below:

在这里插入图片描述

12.8 What are the advantages of using exception handling mechanism in a program?

Answer:

We often come across some peculiar problems other than logic or syntax errors. These error occurs at run time and the whole program may be crashed. To avoid these types of errors we use exception handling mechanism in a program.

12.9 When should a program thrown an exception?

Answer:

When an exception is detected in try block then a program should throw an exception to catch block.

12.10 When is a catch(…) handler is used?

Amswer:

To catch all exceptions catch(…) handler is used.

12.11 What is an exception specification?When is it used?

Answer:

Exception specification is a way to restrict a function to throw only certain specified exceptions. The general form of using an exception specification is:

type function (argument list) throw (type-list)
{
	function body
}

12.12 What should be placed inside a “try” block?

Answer:

A throw statement should be placed inside a try block.

12.13 What should be placed inside a “catch” block?

Answer:

A appropriate message for which an exception is caught shoud be placed in catch block.

12.14 When do we use multiple “catch” handlers?

Answer:

When there are more than one exception in a program, then we use multiple catch statements.

Programming Exercises

12.1 Write a function template for finding the minimum value contained in an array.

#include <iostream>
using namespace std;

const int size = 5;

template <class T>
class vector
{
    T v[size];
public:
    vector(){}
    vector(T *b);
    void show();
    T minimum(vector<T> &m);
};

template <class T>
vector<T>::vector(T *b)
{
    for(int i=0;i<size;i++)
        v[i] = b[i];
}

template<class T>
T vector<T>::minimum(vector<T> &m)
{
    int j = 0;
    for(int k=1;k<size;k++)
    {
        if(m.v[j]>m.v[k])
            j = k;
    }
    return m.v[j];
}

template<class T>
void vector<T>::show()
{
    cout << "(";
    for(int t=1;t<size;t++)
        cout << ", " << v[t];
    cout << " )" << endl;
}

int main()
{
    int x[size] = {5, 7, 3, 1, 8};
    float y[size] = {1.2, 1.5, 3.1, 1.1, 0.501};
    vector<int> v1;
    vector<float> v2;
    v1 = x;
    v2 = y;

    cout << "Minimum value = " << v1.minimum(v1) << " of array";
    v1.show();

    cout << "Minimum value = " << v2.minimum(v2) << " of array";
    v2.show();

    return 0;
}

12.2 Write a program containing a possible exception. Use a try block to throw it and a catch block to handle it promptly.

#include <iostream>
#include <cmath>
#define PI 3.1416
using namespace std;

void power_factor(float a)
{
    if(a>1 || a<-1)
        throw(a);
    else
        cout << "Voltage(V) is lagging from current(I) by : "<< acos(a)*180/PI << "degree\n";
}

int main()
{
    float a;
    try
    {
        cout << "Enter power factor ";
        cin >> a;
        power_factor(a);
    }
    catch(float b)
    {
        cout << "Caught an exception \n";
    }
    return 0;
}

12.3 Wrtie a program that demonstrates how certain exception types are not allowed to be thrown.

#include <iostream>
using namespace std;

void empty() throw()
{
    cout << "In empty()\n";
}

void with_type(float x) throw(int)
{
    if(x==1)
        throw (1);
    else if (x==1.1)
        throw(2.1);
}

int main()
{
    try
    {
        empty();
        with_type(1);
    }
    catch(int n)
    {
        cout<< "Caught an int = " << n;
    }
    catch(float)
    {
        cout<<"Caught a float ";
    }

    return 0;
}

12.4 Write a program to demonstrate the concept of re-throwing an exception.

#include <iostream>
using namespace std;

void division(int a, int b)
{
    try
    {
        if(b==0)
            throw b;
        else
            cout << " a/b = " << (float)a/b << endl;
    }
    catch(int)
    {
        cout << "Caught an exception as first throwing \n";
        throw;
    }
}

int main()
{
    int a, b;
    cout << "Enter the value of a & b : ";
    cin >> a >> b;
    try
    {
        division(a, b);
    }
    catch(int)
    {
        cout << "Caught an exception as re-throwing \n";
    }

    return 0;

12.5 Write a main program that calls a deeply nested function containing an exception. Incorporate necessary exception handling mechanism.

#include <iostream>
using namespace std;
long int square(int i)
{
    return i*i;
}

long int sum(int n)
{
    long int s;
    s = 0;
    for(int i=1;i<=n;i++)
    {
        s+=square(i);
    }

    return s;
}

void display(int m)
{
    try
    {
        if(m<0)
            throw m;
        else
            cout << sum(m)<<endl;
    }
    catch(int n)
    {
        cout<<"Caught an exception \n";
    }
}

int main()
{
    int n;
    cout << "Enter a positive number ";
    cin>>n;
    display(n);
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值