Operator overloading via pointers
dict.cpp:133: invalid operands of types `dict<main()::type>*' and `
dict<main()::type>*' to binary `operator*'
When i use the objects directly i get no compiler faults, but then only part of the objects are sent in to the function and i get segmentation fault.
# include <iostream>
# include <cstdlib>
# include <cstring>
# include <cstdio>
# include <string>
# include <list>
# define NUMASC 128 /* # ASCII-values */
using namespace std;
template <class detype> class dictElem{
public:
detype data;
string key;
dictElem(string k, detype d){
key = k;
data = d;
}
};
template <class dtype> class dict{
public:
typedef dictElem<dtype> dictE;
typedef list <dictE> listOfDictElems;
typedef list <dictE> *arrayOfLists;
arrayOfLists a;
dict(){
a = new listOfDictElems[NUMASC];
}
void dictadd(string key, dtype data){
int idx = hash(key);
dtype *tmp;
if((tmp = dictIdx(key, idx)) != NULL){
*tmp = data;
return;
}
a[idx].push_back(*(new dictE (key , data)));
}
bool dictDel(string key){
int idx = hash(key);
typename listOfDictElems::iterator it;
for(it = a[idx].begin(); it != a[idx].end(); ++it)
if(it->key == key){
a[idx].erase(it);
return true;
}
return false;
}
dtype *dictIdx(string pipe, int idx = -1){
if(idx == -1)
idx = hash(pipe);
typename listOfDictElems::iterator it;// Ensure the compiler that listOf... is a typename
for(it = a[idx].begin(); it != a[idx].end(); ++it)
if(it->key == pipe)
return &(it->data);
return NULL;
}
void delDict(){
int i = 0;
for(i = 0; i < NUMASC; i++)
if(!a[i].empty())
a[i].clear();
delete [] a;
}
int hash(string base){
string::size_type len = base.length();
unsigned int i;
int val = 0;
for(i = 0; i < len; i++){
val += base[i];
}
return (val % NUMASC);
}
void printdict(){
int i, node;
cout << "[DICT START]\n";
for(i = 0; i < NUMASC; i++)
if(!a[i].empty()){
node = 0;
cout << "array[" << i << "]:\n";
typename listOfDictElems::const_iterator it;
for(it=a[i].begin(); it!=a[i].end(); ++it)
cout << "\tNode " << node++ << "\t[Key : " << it->key << "]\n\t\t[Data: " << it->data << "]\n";
}
cout << "[DICT END]\n";
}
dict<dtype> *operator * (dict<dtype> *b){
dict<dtype> *ret = new dict<dtype>;
int i;
for(i = 0; i < NUMASC; i++){
copy(b->a[i].begin(), b->a[i].end(), ret->a[i].begin());
copy(this->a[i].begin(), this->a[i].end(), ret->a[i].end());
}
return ret;
}
};
int main(){
typedef string type;
typedef dictElem<type> dictE;
typedef list <dictE> listOfDictElems;
typedef list <dictE> *arrayOfLists;
dict<type> *d = new dict<type>;
(*d).dictadd("key1", "string");
(*d).dictadd("kex2", "data");
(*d).dictadd("key2", "dd");
(*d).dictadd("key3", "test");
(*d).printdict();
(*d).dictDel("key1");
(*d).printdict();
(*d).delDict();
dict<type> *e = new dict<type>;
(*e).dictadd("tt1", "string");
(*e).dictadd("tt2", "data");
(*e).dictadd("tt3", "dd");
(*e).dictadd("tt4", "test");
(*e).printdict();
cout << "here\n";
dict<type> *p = d*e;
cout << "here2\n";
(*p).printdict();
}

