C++ 正在使用垃圾值覆盖成员变量
在一个类中,我有一个成员变量,当我调用一个方法并能够打印它时,该变量被设置,但当我第二次尝试打印它时,它被重写。 下面是发生的事情的大概代码 诺德泽罗C++ 正在使用垃圾值覆盖成员变量,c++,pointers,C++,Pointers,在一个类中,我有一个成员变量,当我调用一个方法并能够打印它时,该变量被设置,但当我第二次尝试打印它时,它被重写。 下面是发生的事情的大概代码 诺德泽罗 #ifndef NODEZERO_H #define NODEZERO_H //does nothing but sets three properties let say m_a, m_b and m_c. #endif nodefirst.h #ifndef NODEFIRST_H #define NODEFIRST_H #include
#ifndef NODEZERO_H
#define NODEZERO_H
//does nothing but sets three properties let say m_a, m_b and m_c.
#endif
nodefirst.h
#ifndef NODEFIRST_H
#define NODEFIRST_H
#include "nodezero.h"
class nodefirst {
public:
nodezero* root=nullptr;
void insert(int, int, int);
};
#endif
nodefirst.cpp
void nodefirst::insert(int a, int b, int c) {
nodezero realnode = nodezero(a,b,c);
nodezero* node = &realnode;
root = node;
return;
}
test.cpp
#include "nodezero.h"
#include "nodefirst.h"
#include <iostream>
using namespace std;
int main() {
nodefirst nf;
nf.insert(1,2,3);
cout<<nf.root->n_a<<"test"<<nf.root->n_a;
#包括“nodezero.h”
#包括“nodefirst.h”
#包括
使用名称空间std;
int main(){
nodefirst-nf;
nf.插入(1,2,3);
当控件离开时,coutnodezero realnode
将被销毁nodefirst::insert()
。指向它的指针(root
)将悬空,通过它访问内容将导致未定义的行为。使用new
创建节点以使其比函数更长寿。您可能希望使用root=new nodezero(1、2、3)
谢谢大家。不知怎么错过了这个错误。nodezero realnode
在控件离开时被销毁nodefirst::insert()
。指向它的指针(root
)变得悬空,通过它访问内容会导致未定义的行为。请使用new
创建节点,使其比函数寿命长。您可能希望使用root=new nodezero(1,2,3);
谢谢各位。不知怎的错过了错误。