一.Object类的定义:
#ifndef _OBJECT_H
#define _OBJECT_H
class Object{
public:
Object(){}
Object(std::string addr)
:address(addr){
}
~Object(){}
std::string getAddress() const{
return address;
}
private:
std::string address;
};
#endif
二.Client类的定义:
#ifndef _CLIENT_H
#define _CLIENT_H
class Client{
public:
Client(){}
Client(int arg1,double arg2,std::string arg3)
:_arg1(arg1),_arg2(arg2),address(arg3){
}
~Client(){}
void toString(){
std::cout<<"_arg1->"<<_arg1<<std::endl;
std::cout<<"_arg2->"<<_arg2<<std::endl;
std::cout<<"address->"<<address<<std::endl;
}
std::string getAddress() const{
return address;
}
private:
int _arg1;
double _arg2;
std::string address;
};
#endif
三.HashProcessor的定义:
#ifndef _HASH_PROCESSOR_H
#define _HASH_PROCESSOR_H
#include <Poco/HashMap.h>
#include <iostream>
#include "client.h"
#include "object.h"
class HashProcessor{
public:
HashProcessor(){};
~HashProcessor(){};
public:
void addClient(Client* cli);
void removeClient(const Object& obj);
Client* getClient(const Object& obj);
int getClientCount();
private:
Poco::HashMap<std::string,Client*> _objMap;
};
#endif
四.HashProcessor类的实现:
#include "HashProcessor.h"
int HashProcessor::getClientCount(){
return _objMap.size();
}
void HashProcessor::removeClient(const Object& obj){
Poco::HashMap<std::string,Client*>::Iterator it = _objMap.find(obj.getAddress());
if(it != _objMap.end()){
Client* ci = it->second;
std::cout<<"********** start remove **********"<<std::endl;
_objMap.erase(it);
std::cout<<"********** finish remove ***********"<<std::endl;
delete ci;
}
}
void HashProcessor::addClient(Client* cli){
_objMap.insert(std::pair<std::string,Client*>(cli->getAddress(),cli));
}
Client* HashProcessor::getClient(const Object& obj){
Poco::HashMap<std::string,Client*>::Iterator it = _objMap.find(obj.getAddress());
if(it != _objMap.end()){
return it->second;
}
return NULL;
}
五.Main函数的实现:
#include "HashProcessor.h"
#include <iostream>
int main(int argc,char** argv){
HashProcessor processor;
Client* cli = new Client(25,99,"linyanwen");
std::cout<<"obj count->"<<processor.getClientCount()<<std::endl;
processor.addClient(cli);
std::cout<<"obj count->"<<processor.getClientCount()<<std::endl;
Object obj("linyanwen");
Client* ci = processor.getClient(obj);
ci->toString();
processor.removeClient(obj);
std::cout<<"obj count->"<<processor.getClientCount()<<std::endl;
return 0;
}
PS:初写文章,文笔生涩之处,各位请见谅,若有疑问或者交流的,可加本人YY号:301558660
转载请注明出处:山水间博客,http://blog.youkuaiyun.com/linyanwen99/article/details/8031990