함수 포인터의 매우 기본적인 해시 맵을 만들어야합니다. 내 요구 사항은 단지 값을 추가 한 다음 키를 기반으로 값을 얻는 것입니다. 어떤 정치적인 이유로, 나는 표준 librabry를 사용할 수 없습니다. 나는 잘 작동하는 코드를 가지고있다. 하지만 클래스 함수를 가리키는 함수 포인터를 원한다면이 함수는 작동하지 않습니다. 어떤 제안이 아래 코드에서 수정되어야합니다.함수 포인터 (클래스 멤버 함수)의 HashMap
이 PING 및 REFRESH는 독립적 인 기능입니다. 그래서이 코드는 작동합니다. 그러나 이러한 함수를 HashMap 클래스로 옮기면 실패합니다.
코드 : -
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <iomanip>
using namespace std;
typedef void (*FunctionPtr)();
void ping(){
cout<<"ping";
}
void refresh(){
cout<<"refresh";
}
class HashEntry {
private:
int key;
FunctionPtr func_ptr1;;
public:
HashEntry(int key, FunctionPtr fptr) {
this->key = key;
this->func_ptr1 = fptr;
}
int getKey() {
return key;
}
FunctionPtr getValue() {
return this->func_ptr1;
}
};
const int TABLE_SIZE = 128;
class HashMap {
private:
HashEntry **table;
public:
HashMap() {
table = new HashEntry*[TABLE_SIZE];
for (int i = 0; i < TABLE_SIZE; i++)
table[i] = NULL;
}
FunctionPtr get(int key) {
int hash = (key % TABLE_SIZE);
while (table[hash] != NULL && table[hash]->getKey() != key)
hash = (hash + 1) % TABLE_SIZE;
if (table[hash] == NULL)
return NULL;
else
return table[hash]->getValue();
}
void put(int key, FunctionPtr fptr) {
int hash = (key % TABLE_SIZE);
while (table[hash] != NULL && table[hash]->getKey() != key)
hash = (hash + 1) % TABLE_SIZE;
if (table[hash] != NULL)
delete table[hash];
table[hash] = new HashEntry(key, fptr);
}
~HashMap() {
for (int i = 0; i < TABLE_SIZE; i++)
if (table[i] != NULL)
delete table[i];
delete[] table;
}
};
void main(){
HashMap* pHashsMap = new HashMap();
pHashsMap->put(1,ping);
pHashsMap->put(2,refresh);
pHashsMap->put(3,ping);
pHashsMap->put(4,refresh);
pHashsMap->put(5,ping);
pHashsMap->put(6,refresh);
cout<<" Key 1---"<<pHashsMap->get(1)<<endl;
pHashsMap->get(1)();
cout<<" Key 5---"<<pHashsMap->get(5)<<endl;
pHashsMap->get(5)();
cout<<" Key 3---"<<pHashsMap->get(3)<<endl;
pHashsMap->get(3)();
cout<<" Key 6---"<<pHashsMap->get(6)<<endl;
pHashsMap->get(6)();
delete pHashsMap;
}
'main'은'int'를 반환합니다. –