3

Im implementing a B+Tree for a class. The Nodes are currently implemented like this:

class Node {
    public:
        E* keys[order*2];
        Node *children[order*2+1];
        int size;
        Node(){ 
            size = 0;
        }
        bool empty() {
            return size == 0;
        }
        bool isLeafNode() {
            return false;
        }
};

class LeafNode : public Node {
    public:
        E* data[order*2+1];
        bool isLeafNode() {
            return true;
        }
};

When I want to add an element to a leaf node (by accessing LeafNode->data), I get

 error: request for member ‘data’ in ‘left<int>’, which is of non-class type ‘BTree<int>::LeafNode*()’

I guess this happens because the compiler doesn't know whether the Node I'm accessing is an inner- or leaf-node, although I'm checking it first by using isLeafNode(). I can't merge the two classes into one, because the Leaf Nodes need one more Bucket for the data than the inner nodes.

I realize this is sort of a design-question, but is there some trivial approach to this problem that I'm missing? I'm fairly new to C++.

4

2 回答 2

4

你真的应该为这样的事情使用虚拟方法。您可以更改isLeafNode()查询以返回指向叶节点的指针(如果它为 1),否则返回 NULL。

class LeafNode; // forward declare

class Node {
//...
public:
    virtual ~Node () {}
    virtual LeafNode * isLeafNode () { return 0; }
    //...
};

class LeafNode : public Node {
//...
public:
    LeafNode * isLeafNode () { return this; }
    //...
};

然后,您可以使用此方法从 aNode访问dataif 它实际上是 a LeafNode

于 2013-04-30T18:29:29.660 回答
0

错误信息

error: request for member ‘data’ in ‘left<int>’, which is of non-class type  ‘BTree<int>::LeafNode*()’

这种形式的其他错误通常意味着您正在尝试struct使用 a访问 a 的字段,.而您应该使用->. 例如,如果您有

LeafNode* ptr = /* ... */;
ptr.data[0] = /* ... */;

您将在第二行收到错误,因为您使用.的是->.

尝试查看这是否是您在指示线上遇到的错误,如果是,请将点更改为箭头。

希望这可以帮助!

于 2013-04-30T18:35:28.960 回答