-1

对 C++ 来说很新,我正在尝试为几天后到期的项目编写二进制堆计算器。在进入二叉堆之前,我想编写一个二叉树结构作为堆的超类。

我仍在尝试围绕指针与引用以及每个指针在分配时的样子以及何时应该将某些东西定义为指针或引用。

无论如何,这里有一些我很好奇的代码:

#include "BinaryTree.h"

int main(void){

    BinaryTree tempTree = new BinaryTree();
    BinaryNode* ptrToRoot;
    ptrToRoot = tempTree.getRootNode();

    int inputArr = { 5, 2, 7, 10, 11, 20, 1};

    for(int i = 0; i < sizeof(inputArr) / sizeof(inputArr[0]); i++){
            tempTree.binaryTreeInsert(ptrToRoot, inputArr[i]);
    }

    tempTree.inOrderPrint(ptrToRoot);
}

而且我从对 binaryTreeInsert 和 inOrderPrint 的调用中都收到了错误,它们都将 ptrToRoot 作为参数。错误说“无效的参数......有效的候选人是 BinaryNode *, int。

但是当我将鼠标悬停在 Eclipse 中的每个参数上时,它们都显示它们是必需的类型。

我是否错误地定义了指针?这是我的 BinaryTree 类的头文件,以防万一:

#ifndef BINARYTREE_H_
#define BINARYTREE_H_

#include "BinaryNode.h"

struct BinaryTree  {

    BinaryTree();
    virtual ~BinaryTree(){}

    BinaryNode rootNode;
    int noOfNodes;

    BinaryNode* getRootNode(){ return rootNode; }

    int countNodes(BinaryNode* ptRootNode);
    bool binaryTreeContains( BinaryNode* ptRootNode, int element);
    void binaryTreeInsert(BinaryNode* ptRootNode, int element);
    void preorderPrint( BinaryNode *ptRootNode );
    void postorderPrint( BinaryNode *ptRootNode );
    void inorderPrint( BinaryNode *ptRootNode );
};

#endif
4

1 回答 1

0

这可能至少是您问题的一部分:

BinaryTree tempTree = new BinaryTree();

此行不正确;new用于执行堆分配,它返回一个指向新分配对象的指针。但是,您的对象是在堆栈上分配的。

尝试将其更改为:

BinaryTree tempTree;

这将使用无参数构造函数在堆栈上构造一个新对象。这可能会解决您的问题,因为编译器可能会对此变量的类型感到困惑。

于 2012-11-11T04:02:09.997 回答