利用类模板解决绝对值功能

#include <iostream>
#include <stdio.h>
using namespace std;
template <class T>
class Absolute{
private:
    T x;
public:
    T getValue(void)const;
    Absolute(T xx){x=xx;}
};
 template <class T>
T Absolute<T>::getValue()const
{
    if(x<0) return 0-x;
    else return x;
}

int main(void){
    char c='\0';
    int i=0;
    long l=0;
    scanf("%c%d%ld",&c,&i,&l);
    float f=1.1;
    double d=2.2;
    scanf("%f%lf",&f,&d);
    Absolute<char> dc(c);
    cout<<dc.getValue()<<endl;
    Absolute<int> di(i);
    cout<<di.getValue()<<endl;
    Absolute<long> dl(l);
    cout<<dl.getValue()<<endl;
    Absolute<float> df(f);
    cout<<df.getValue()<<endl;
    Absolute<double> dd(d);
    cout<<dd.getValue()<<endl;
    return 0;
}

运行截图如下:

猜你喜欢

转载自blog.csdn.net/y0205yang/article/details/118653221
今日推荐