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
这可能至少是您问题的一部分:
BinaryTree tempTree = new BinaryTree();
此行不正确; new
用于执行堆分配,并返回指向新分配对象的指针。 但是,您的对象是在堆栈上分配的。
尝试将其更改为:
BinaryTree tempTree;
这将使用 no-arg 构造函数在堆栈上构造一个新对象。 这可能会解决您的问题,因为编译器可能会对此变量的类型感到困惑。