C++第六章习题

6.1 为什么使用模板?函数模板声明的一般形式是什么?

         写一个通用的模板可以适用于多种不同的数据类型,使代码的可重用性大大提高,从而提高软件的开发效率。

声明格式:

template<typename 类型参数>

返回类型 函数名(模板形参表)

{

         函数体

}

也可以定义成如下形式

template<class  类型参数>

返回类型 函数名(模板形参表)

{

         函数体

}

6.2 什么是模板实参和模板函数?

6.3. 略

6.4 函数模板与同名的非模板函数重载时,调用的顺序是怎样的?

         先找有没有同名的非模板函数,如果有就调用,如果没有就找函数模板。

6.5-6.7 DAB

6.8

10 0.23

X This is a test.

6.9

4!=24

-2!=n=-2不能计算n!.

程序执行结束。

6.10

其中的最小值是:3

6.11

#include <iostream>
using namespace std;

template <typename T>
T min(T a, T b, T c)
{
    T min;
    min = a < b ? a : b;
    min = min < c ? min : c;
    return min;
}

int main()
{
    cout << min(10,5,3) << endl;
    cout << min(10.0,5.0,3.0) << endl;
    cout << min('a','b','c') << endl;
    return 0;
}

6.12

#include <iostream>
using namespace std;

template <typename T>
T max(T *a, int n)
{
    T max = 0;
    for(int i = 0; i < n; i++)
    {
        if (a[i] > max)
        {
            max = a[i];
        }
    }
    return max;
}

int main()
{
    int aInt[5] = {3,5,4,8,77};
    double bDouble[7] = {25.1,254.6,365.5,254.85,332.5,478.2,255.8};
    cout << max(aInt, 5) << endl;
    cout << max(bDouble,7) << endl;
    return 0;
}

6.13

#include <iostream>
using namespace std;

template <typename T>
T *sort(T *a, int n)
{
    T temp;
    for(int i = 0; i < n-1; i++)
    {
        for(int j = n-1; j > i; j-- )
        {
            if(a[j] < a[j-1])
            {
                temp = a[j];
                a[j] = a[j-1];
                a[j-1] = temp;
            }
        }
    }
    return a;
}

int main()
{
    int aInt[5] = {3,5,4,8,77};
    double bDouble[7] = {25.1,254.6,365.5,254.85,332.5,478.2,255.8};
    sort(aInt,5);
    for(int i = 0; i < 5; i++)
    {
        cout << aInt[i] << " ";
    }
    cout << endl;
    sort(bDouble, 7);
    for(int i = 0; i < 7; i++)
    {
        cout << bDouble[i] << " ";
    }
    cout << endl;
    return 0;
}

6.14

#include <iostream>
using namespace std;

template <typename T>
class sum
{
private:
    T a, b, c;
public:
    sum(T a, T b, T c)
    {
        sum::a = a;
        sum::b = b;
        sum::c = c;
    }
    T getSum()
    {
        return a + b + c;
    }
};

int main()
{
    sum<int> s1(3,5,7);
    cout << s1.getSum();
    return 0;
}

6.15

#include <iostream>
using namespace std;

template <typename T>
class sum
{
private:
    T a, b, c;
public:
    sum(T a, T b, T c);
    T getSum();
};
template <typename T>
sum<T>::sum(T a, T b, T c)
{
    sum::a = a;
    sum::b = b;
    sum::c = c;
}
template <typename T>
T sum<T>::getSum()
{
    return a + b + c;
}

int main()
{
    sum<int> s1(3,5,7);
    cout << s1.getSum();
    return 0;
}
原文地址:https://www.cnblogs.com/tangzhengyue/p/2551909.html