I was building a Huffman coding tree and I wanted to create an array where each position contains a separate tree, as the code follows:
// Number of initial nodes
int number;
cin >> number;
int* weights = new int[number];
for (int i = 0; i < number; i++)
cin >> weights[i];
// Convert to huffman tree with one element
intHuffTree* tree = new intHuffTree[number];
for (int i = 0; i < number; i++) {
tree[i] = intHuffTree(weights[i]);
}
where the class is defined like:
// Huffman tree with integers
class intHuffTree {
private:
// Root of the tree
intHuffNode* Root;
public:
// Leaf constructor
intHuffTree (int freq) { Root = new intLeafNode(freq); }
// Internal constructor
intHuffTree (intHuffTree* l, intHuffTree* r) {
Root = new intIntlNode(l->root(), r->root());
}
// Destructor
~intHuffTree() {};
// Get root
intHuffNode* root() { return Root; }
// Root weight
int weight() { return Root->weight(); }
};
When compiling, I got errors like:
main.cpp: In function ‘int main()’:
main.cpp:19:47: error: no matching function for call to ‘intHuffTree::intHuffTree()’
intHuffTree* tree = new intHuffTree[number];
^
I wonder why I could not initialize the array as I did for the int
array, and is there any possible solution?
Thanks a lot!
intHuffTree* tree = new intHuffTree[number];
The above statement is creating an array of intHuffTree. The array would have 'number' elements. Each element would be of type intHuffTree. To create each element the compiler needs the default constructor which is missing in your code because you have provided overloaded constructors.
If you intend to create a single tree with 'number' elements you need to write it as
intHuffTree* tree = new intHuffTree(number);
If you intend to create an array of 'number' elements of intHuffTree you need to add the constructor with no arguments.
intHuffTree () { /* Do the right things here. */ }