自定义类的C ++数组,没有匹配的函数调用 [英] C++ array of a self-defined class, no matching function call

查看:70
本文介绍了自定义类的C ++数组,没有匹配的函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个霍夫曼编码树,我想创建一个数组,其中每个位置都包含一个单独的树,如下所示:

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]);
}

其中的类定义如下:

// 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(); }
};

编译时出现如下错误:

main.cpp: In function ‘int main()’:
main.cpp:19:47: error: no matching function for call to ‘intHuffTree::intHuffTree()’
     intHuffTree* tree = new intHuffTree[number];
                                               ^

我想知道为什么我不能像对 int 数组那样初始化数组,并且有什么可能的解决方案吗?

I wonder why I could not initialize the array as I did for the int array, and is there any possible solution?

非常感谢!

推荐答案

intHuffTree* tree = new intHuffTree[number];

上面的语句创建一个intHuffTree数组.该数组将具有数字"元素.每个元素的类型为intHuffTree.要创建每个元素,编译器需要代码中缺少的默认构造函数,因为您提供了重载的构造函数.

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.

如果您打算使用"number"个元素创建一棵树,则需要将其写为

If you intend to create a single tree with 'number' elements you need to write it as

intHuffTree* tree = new intHuffTree(number);

如果要创建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. */ }

这篇关于自定义类的C ++数组,没有匹配的函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆