我最近开始使用 C++ 编程(已经用 Java 完成)。我在使用不保留其值的类变量时遇到问题。
bt_builder.h
class BtreeBuilder{
BtreeNode *root; //will point to root of the tree
public:Status insertBuilderKey(KeyId);
.....
}
bt_builder.cpp
Status BtreeBuilder::insertBuilderKey(KeyId k){
....
BtreeIndex newroot ;
newroot.insertKey(Ld.getKey(0),0,left,right);
root = &newroot;
printnode(root);// prints correct values
....
}
bt_main.cpp
int main()
{
BtreeBuilder *btb = new BtreeBuilder();
btb->insertBuilderKey(1);//inside this method it has printed values corretly
btb->printroot();//now it is printing garbage values for root node it seems that the value which was set for root inside the method is no longer there
}
所以我的问题是为什么它不在方法外保留 root
的值,即使它是一个类变量?
这个问题的解决方案是什么。
最佳答案
BtreeIndex newroot ;
在 BtreeBuilder::insertBuilderKey
中在堆栈上创建了一个 BtreeIndex
,但是保存该变量的堆栈帧在该方法后被销毁已完成,因此您的变量也将被销毁。
您需要在堆上创建BtreeIndex
:BtreeIndex* newroot = new BtreeIndex();
参见 http://www.learncpp.com/cpp-tutorial/79-the-stack-and-the-heap/了解更多信息。
关于C++ 类变量不保留值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29825128/