例 9.14 声明一个类模板,利用它分别实现两个整数、浮点数和字符的比较,求出大数和小数。

C++程序设计(第三版) 谭浩强 例9.14 个人设计

例 9.14 声明一个类模板,利用它分别实现两个整数、浮点数和字符的比较,求出大数和小数。

代码块:

在类模板内部定义成员函数

#include 
using namespace std;
template <class numtype>
class Compare
{
public:
    Compare(numtype a, numtype b): x(a), y(b){}
    numtype max()
    {
        return x>y ? x : y;
    }
    numtype min()
    {
        return xprivate:
    numtype x, y;
};
int main()
{
    int m, n;
    cout<<"Please enter m, n: ";
    cin>>m>>n;
    Compare <int>  fa(m, n);
    cout<<"Max="<cout<<"Min="<float s, t;
    cout<<"Please enter s, t: ";
    cin>>s>>t;
    Compare <float> fb(s, t);
    cout<<"Max="<cout<<"Min="<char i, j;
    cout<<"Please enter i, j: ";
    cin>>i>>j;
    Compare <char> fc(i, j);
    cout<<"Max="<cout<<"Min="<"pause");
    return 0;
}

在类模板外定义成员函数

#include 
using namespace std;
template <class numtype>
class Compare
{
public:
    Compare(numtype a, numtype b): x(a), y(b){}
    numtype max();
    numtype min();
private:
    numtype x, y;
};
template <class numtype>
numtype Compare::max()
{
    return x>y ? x : y;
}
template <class numtype>
numtype Compare::min()
{
    return xint main()
{
    int m, n;
    cout<<"Please enter m, n: ";
    cin>>m>>n;
    Compare <int>  fa(m, n);
    cout<<"Max="<cout<<"Min="<float s, t;
    cout<<"Please enter s, t: ";
    cin>>s>>t;
    Compare <float> fb(s, t);
    cout<<"Max="<cout<<"Min="<char i, j;
    cout<<"Please enter i, j: ";
    cin>>i>>j;
    Compare <char> fc(i, j);
    cout<<"Max="<cout<<"Min="<"pause");
    return 0;
}

你可能感兴趣的:(个人设计)