I was bored one day, so I made this library:
template <class X, class Y> class HASH
{
public:
HASH(X element, Y key)
{
elements=new X[0];
keys=new Y[0];
keys[0]=key;
elements[0]=element;
num_elements=0;
};
~HASH ()
{
delete[] elements;
delete[] keys;
};
void Add(X element, Y key)
{
for (int x=0; x<=num_elements; x++)
{
if (keys[x]==key)
{
throw(key);
}
}
//make copy variables
X *copy_elements=new X[num_elements];
Y *copy_keys=new Y[num_elements];
//copy all the elements
for (int x=0; x<=num_elements; x++)
{
copy_elements[x]=elements[x];
copy_keys[x]=keys[x];
}
//delete the originals
delete[] elements;
delete[] keys;
//resize the originals
elements=new X[num_elements+1];
keys=new Y[num_elements+1];
//copy everything back to the originals
for (int x=0; x<=num_elements; x++)
{
elements[x]=copy_elements[x];
keys[x]=copy_keys[x];
}
//delete the copies
delete[] copy_keys;
delete[] copy_elements;
//increment num_elements
num_elements++;
//add the new elements
elements[num_elements]=element;
keys[num_elements]=key;
};
X operator [] (Y key)
{
int num=0;
for (int x=0; x<=num_elements; x++)
{
if (keys[x]==key)
{
num=x;
break;
}
}
return elements[num];
};
Y KeyNum(int x)
{
return keys[x];
};
int NumElements()
{
return num_elements;
};
private:
int num_elements;
X *elements;
Y *keys;
};
and then I tested it, and it worked. So now I am trying to create an experiment whose source code is this:
#include <hash.cpp>
#include <iostream>
using namespace std;
class OBJECT
{
public:
OBJECT(string name, int number)
{
int_properties=new HASH <string, int>;
};
~OBJECT()
{
delete int_properties;
};
HASH <string, int> *int_properties;
};
int main()
{
OBJECT a("name", 5);
return 0;
}
and it is returning the error:
brain.cpp: In constructor ‘OBJECT::OBJECT(std::string, int)’: brain.cpp:10: error: no matching function for call to ‘HASH<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int>::HASH()’ /usr/include/hash.cpp:4: note: candidates are: HASH<X, Y>::HASH(X, Y) [with X = std::basic_string<char, std::char_traits<char>, std::allocator<char> >, Y = int] /usr/include/hash.cpp:2: note: HASH<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int>::HASH(const HASH<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int>&)
I have made a whole lot of tests, and no matter what I do, I can't seem to initialize an object that is the data-member of another object. I just don't understand why.
new T[n]
is legal whenn
is zero, there's very little you can do with the result. – aschepler