问题
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!
回答1:
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. */ }
回答2:
Take your code:
new intHuffTree[number];
What this is saying is "create N intHuffTrees using its default constructor", where N is number
. You don't have a default constructor, which is what the error message is trying to tell you.
Looking at your code, perhaps you intended to pass number
to the constructor instead? In which case, the code would be:
new intHuffTree(number);
Note that change in brackets.
回答3:
This
intHuffTree* tree = new intHuffTree[number];
attemps to allocate an array with number
elements. To do so, a default constructor would be called (one that can be called without parameters), but your class has none.
When you don't need to deal with manual dynamic memory, then don't. To create an instance you could write
InHuffTree tree(number);
If you want to create an array with number
elements you need to supply a default constructor.
来源:https://stackoverflow.com/questions/61457826/c-array-of-a-self-defined-class-no-matching-function-call