u012777670 2015-07-05 04:17 采纳率: 0%
浏览 1515

C++中使用指针引用的问题

#include
#include
using namespace std;

struct BSTNode
{
BSTNode left;
BSTNode *right;
int data;
BSTNode(int value){
data=value;
left=NULL;
right=NULL;
}
};
class BST{
public:
BST(){
root=NULL;
}
void insert(BSTNode *&ptr,int value){
if(ptr==NULL){
ptr=new BSTNode(value);
return ;
}
else if(ptr->data>value) insert(ptr->left,value);
else if(ptr->dataright,value);
else return ;
}
bool remove(BSTNode *&ptr,int value){
return false;
}
void printtree(BSTNode *ptr){
if(ptr!=NULL){
queue<BSTNode
> myque;
myque.push(ptr);
BSTNode temp;
while(!myque.empty()){
temp=myque.back();
myque.pop();
cout<data<<" ";
if(temp->left!=NULL) myque.push(temp->left);
if(temp->right!=NULL) myque.push(temp->right);
}
}
}
BSTNode
getroot(){
return root;
}
//public:
BSTNode *root;
};

void main(){
BST *tree = new BST;
int value;
cout<<"二叉搜索树为"< tree->printtree(tree->getroot());
cout< cin>>value;
// int &a=value;
// int &b=4;
while(value!=EOF){
tree->insert(tree->root,value);//通过指针直接获得root,函数调用的参数不会出错
tree->insert(tree->getroot(),value);//通过get方法获得root,函数调用的参数出错,提示“非常量引用的初始值必须为左值”
BSTNode *test = tree->getroot();//如果先通过get方法获得root并赋值给test,在将test传递给函数,参数不会出错
tree->insert(test,value);
cout<getroot()<<"-----"<root;
cout<<"二叉搜索树为"< tree->printtree(tree->getroot());
cout< cin>>value;
}
}
通过函数获得数据成员和通过指针获得数据成员有什么区别?

  • 写回答

2条回答

  • 91program 博客专家认证 2015-07-05 06:36
    关注

    因为通过指针,可以修改成员的数值;但是通过函数呢,Get 就之是获取、没有赋值的功能。

    tree 在 new 之后,还没有赋值。所以,要求后续的操作只能使用成员、不能使用函数。因为此时函数还未完成初始化!

    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学中在线排序的时间在线排序的在线LPT算法
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧