[GeekBand][STL与泛型编程]第二周作业

1. 先上结果

20m
11200m
20s
10000s
10
请按任意键继续. . .

2. 源代码

文件1:Measurement-Test.cpp
#include 
#include "Measurement.h"
using namespace std;

int main()
{
    Measurement m1 = 20;
    Measurement m2 = 11.2;
    meter me = m1.description();

    Measurement m3 = 20;
    Measurement m4 = 10;

    Measurement m5 = 10;

    cout << me << endl;
    cout << m2.description() << endl;
    cout << m3.description() << endl;
    cout << m4.description() << endl;
    cout << m5.description() << endl;

    return 0;
}
文件2:Measurement.h
#ifndef __MEASUREMENT__
#define __MEASUREMENT__

#include 
#include 

template
struct Measurement;
template
struct Measurement_Traits;
struct meter;
struct kilometer;
struct second;
struct minute;
std::ostream& operator<<(std::ostream& os, const meter& m);
std::ostream& operator<<(std::ostream& os, const second& s);

template
struct Measurement
{
    double data;
    typedef typename Measurement_Traits::Unit_Type Unit_Type;
    Unit_Type description()
    {
        return Unit_Type(Measurement_Traits::ratio*this->data);
    }
    Measurement(double x)
        :data(x)
    {}
};

template
struct Measurement_Traits
{
    typedef double Unit_Type;
    static const double ratio;
};
template
const double Measurement_Traits::ratio = 1;

template<>
struct Measurement_Traits
{
    typedef meter Unit_Type;
    static const double ratio;
};

template<>
struct Measurement_Traits
{
    typedef meter Unit_Type;
    static const double ratio;
};

template<>
struct Measurement_Traits
{
    typedef second Unit_Type;
    static const double ratio;
};

template<>
struct Measurement_Traits
{
    typedef second Unit_Type;
    static const double ratio;
};

struct meter
{
    double data;
    static const std::string unit_text;
    meter(double x) :data(x) {}
};

struct kilometer
{
    double data;
    static const std::string unit_text;
};

struct second
{
    double data;
    static const std::string unit_text;
    second(double x) :data(x) {}
};

struct minute
{
    double data;
    static const std::string unit_text;
};

#endif // !__MEASUREMENT__
文件3:Measurement.cpp
#include "Measurement.h"

const double Measurement_Traits::ratio = 1;
const double Measurement_Traits::ratio = 1000;
const double Measurement_Traits::ratio = 1;
const double Measurement_Traits::ratio = 1000;
const std::string meter::unit_text = "m";
const std::string kilometer::unit_text = "km";
const std::string second::unit_text = "s";
const std::string minute::unit_text = "min";

std::ostream & operator<<(std::ostream & os, const meter & m)
{
    return os << m.data << m.unit_text;
}

std::ostream & operator<<(std::ostream & os, const second & s)
{
    return os << s.data << s.unit_text;
}

你可能感兴趣的:([GeekBand][STL与泛型编程]第二周作业)