C++ 类变量不保留值

标签 c++

我最近开始使用 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/

相关文章:

c++ - Qt 客户端-服务器应用程序, “send image” 有问题

c++ - vector 必须与其分配器具有相同的值

c++ - 在 C++ DLL 项目中使用 STL

C++ - 检查 cin 是否有错误

c++ - 编写我自己的字符串类但得到 "reference to ‘string’ 是不明确的“编译错误

c++ - OpenSSL偶尔会打印随机垃圾

C++:在文本文件中存储 char 数组时是否存储 Null?

javascript - 从c++访问qml元素id

iphone - 如何在实现文件中运行一个函数?

c++ - 将 Bitset 数组转换为 vector <bool>