c++类模版和运算符重载的运用

来源:互联网 发布:封面制作软件下载 编辑:程序博客网 时间:2024/05/22 09:50

最近在看数据结构算法c++描述,很久没写c++了,所以就当回忆下,所以以下代码就当练手,输出的是工资的最大值人的姓名和它的工资:

#include<iostream>#include<vector>#include<string>using namespace std;template <typename Compareable> //模版const Compareable & findMax(const vector<Compareable> & arr) //Compareable可以表示任意类型,这里是表示Employee类{    int maxIndex = 0;    for(int i=1; i<arr.size(); i++)    {        if(arr[maxIndex] < arr[i])        {            maxIndex = i;        }    }    return arr[maxIndex];}class Employee //雇员的类{public:    void setVaule(const string & n,double s) //构造函数初始化,两个参数    {        name = n;        salary = s;    }    const string & getName() const //返回员工的姓名    {        return name;    }    void print(ostream &out) const //要输出的东西    {        out << name << "(" << salary << ")";    }    bool operator < (const Employee & rhs) const //运算符重载    {        return salary < rhs.salary;    }private:    string name;    double salary;};ostream & operator << (ostream &out,const Employee & rhs) //输出流{    rhs.print(out);     return out;}int main(){    vector<Employee> v(3); //vector数组,表示容器内有三个vaule    v[0].setVaule("George Bush",400000.00);    v[1].setVaule("Bill Gates",20000000.00);    v[2].setVaule("Dr.Phil",130000000.00);    cout<<findMax(v)<<endl; //如果没有用输出流的话,那么这句会报错}

0 0
原创粉丝点击