-1

这是我的代码:

using namespace std;

class HuffmanTree
{
public: 
    int frequency;

    HuffmanTree(){}
    HuffmanTree(int freq)
    {
        frequency = freq;
    }

    int compareTo(HuffmanTree tree)
    {
        return frequency - tree.frequency;
    }
}

class HuffmanLeaf : public HuffmanTree
{
public:
    char value;

    HuffmanLeaf(int freq, char val)
    {
        HuffmanTree(freq);
        value = val;
    }
}

class HuffmanNode : public HuffmanTree
{
public:
    HuffmanTree left, right;

    HuffmanNode(HuffmanTree l, HuffmanTree r)
    {
        HuffmanTree(l.frequency + r.frequency);
        left = l;
        right = r;
    }
}

class HuffmanCode
{
    static HuffmanTree buildTree(int charFreqs[])
    {
        priority_queue<HuffmanTree> pq;

        for(int i = 0; i < sizeof(charFreqs)/sizeof(char); i++)
        {
            if(charFreqs[i] > 0)
                pq.push(HuffmanLeaf(charFreqs[i], (char)i));
        }
        while (pq.size() > 1)
        {
            // two trees with least frequency
            HuffmanTree a = pq.top();
            pq.pop();
            HuffmanTree b = pq.top();
            pq.pop();

            // put into new node and re-insert into queue
            pq.push(HuffmanNode(a, b));
        }
        HuffmanTree c = pq.top();
        pq.pop();
        return c;
    }
}

static void printCodes(HuffmanTree tree, string prefix) {
    //assert tree != null;
    HuffmanTree* baseClass;
    HuffmanLeaf* leafClass;
    HuffmanNode* nodeClass;
    if (typeid(*baseClass) == typeid(HuffmanLeaf)) 
    {
        HuffmanLeaf leaf = (HuffmanLeaf)tree;

        // print out character, frequency, and code for this leaf (which is just the prefix)
        cout<<leaf.value<<"\t"<<leaf.frequency<<"\t"<<prefix;
    }
    else if (typeid(*baseClass) == typeid(HuffmanNode)) 
    {
        HuffmanNode node = (HuffmanNode)tree;

        // traverse left
        prefix.append("0");
        printCodes(node.left, prefix);
        prefix.erase(prefix.length()-1);

        // traverse right
        prefix.append("1");
        printCodes(node.right, prefix);
        prefix.erase(prefix.length()-1);
    }
}

我不知道如何解决线路失败的问题

HuffmanNode node = (HuffmanNode)tree;
HuffmanLeaf leaf = (HuffmanLeaf)tree;

我知道它与类型转换有关,并且我对 dynamic_cast、static_cast 和其他两个进行了研究,但我似乎无法弄清楚它的要求。任何帮助,将不胜感激。如果您发现任何其他问题,请告诉我。

4

1 回答 1

3

垂头丧气是违法的。AHuffmanTree既不是 aHuffmanNode也不是 a HuffmanLeaf,而是相反。

你试图做的事情并没有真正的意义。为什么要将 a 转换HuffmanTree为 aHuffmanNode或 a HuffmanLeaf

无论哪种方式,要编译它(但同样,它没有意义),您必须为HuffmanNodeorHuffmanLeaf或 add operator HuffmanNode()and operator HuffmanLeaf()to声明转换构造函数HuffmanTree

于 2012-04-16T19:55:33.340 回答