1.任务是实现一个投票系统.
2.投票规则:
- 1.每个投票者只可以投一次票。投票者通过生成的随机数,在第一个到最后一个候选人之间选择一个候选人来进行投票。
- 2.每一个候选人都保存着投票者给他们投票的记录。
- 3.选举之后,拥有最高投票数的候选人当选。
主要需要的类有Person(作为Voter和Candidate的父类)、Voter类(投票者类)、Candidate(选举者类)、PersonSet类(容器类).
Person.hpp
#ifndef Person_hpp
#define Person_hpp
#include <iostream>
#include <cstring>
using namespace std;
class Person{
protected:
char* _name;
int _age;
double _salary;
int _id;
static int _totalPersons;//可用于id累加
public:
Person(const char* name,int age,double salary);
void SetAge(int newAge);
void SetSalary(double newSalary);
int getAge();
int getSalary();
void setTotalPerson(int t);
void setID(int id);
friend ostream& operator<<(ostream& out,Person& p);
Person& operator=(Person& p);
void print();
~Person();
};
#endif /* Person_hpp */
Person.cpp
// Person.cpp
#include "Person.hpp"
int Person::_totalPersons=0;
Person::Person(const char* name,int age,double salary){
_name = new char[strlen(name)+1];
strcpy(_name, name);
_age = age;
_salary = salary;
_totalPersons++;
_id = _totalPersons;
}
void Person::SetAge(int newAge){
_age = newAge;
}
void Person::SetSalary(double newSalary){
_salary = newSalary;
}
void Person::setTotalPerson(int t){
_totalPersons = t;
}
void Person::setID(int id){
_id = id;
}
int Person::getAge(){
return _age;
}
int Person::getSalary(){
return _salary;
}
ostream& operator<<(ostream& out,Person& p){
out<<"ID:"<<p._id<<endl;
out<<"name:"<<p._name<<endl;
out<<"age:"<<p._age<<endl;
out<<"salary:"<<p._salary<<endl;
out<<"--------------------------------------------\n";
return out;
}
Person& Person::operator=(Person& p){
if(this!=&p){
delete [] _name;
_name = new char[strlen(p._name)+1];
strcpy(_name, p._name);