Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/142.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 正在使用垃圾值覆盖成员变量_C++_Pointers - Fatal编程技术网

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);

当控件离开时,cout
nodezero realnode
将被销毁
nodefirst::insert()
。指向它的指针(
root
)将悬空,通过它访问内容将导致未定义的行为。使用
new
创建节点以使其比函数更长寿。您可能希望使用
root=new nodezero(1、2、3)
谢谢大家。不知怎么错过了这个错误。
nodezero realnode
在控件离开时被销毁
nodefirst::insert()
。指向它的指针(
root
)变得悬空,通过它访问内容会导致未定义的行为。请使用
new
创建节点,使其比函数寿命长。您可能希望使用
root=new nodezero(1,2,3);
谢谢各位。不知怎的错过了错误。