在一个类中,我有一个成员变量,该成员变量在调用方法时可以设置并能够打印,但是在我尝试第二次打印时会被覆盖。 下面是发生的事情的大概代码。
nodezero.h
#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;
调用cout时,“ test”之前的部分正确打印为1,但test之后的部分为垃圾值。 有人可以帮我吗?我找不到我想要的东西。