c++中如何保留指针的值而不覆盖它

How can you preserve the value of a pointer in c ++ without overwriting it

我有一个更复杂的项目的沙箱代码:

#include <sstream>
#include <iostream>
#include <vector>

using namespace std;

class Table
{
    friend class Variable;
public:
    Variable * variables[1021];
};

class Variable
{
    friend class Nodo;
public:
    char clas;
    Nodo * ini;
};

class Nodo
{   
public:
    char clas;
    Variable * father;
private:
    float * value;
public:
    Nodo();
    void set_value(float);
    float * get_value();
};


Nodo::Nodo()
{
    clas = ' ';
    father = NULL;
    value = NULL;
}

void Nodo::set_value(float m)
{
    float * r = new float();
    r = &m;
    value = (float *)r;
}

float * Nodo::get_value() 
{
    return this->value;
}

这是主要的:

void main ()
{
    Nodo * n = new Nodo();    // OK.
    n->set_value(5.3442);     // Ok. 

    Variable * v = new Variable();      // This is the problem.

    // When I declare another pointer an initilized it, n lost the value stored in value. 

    Variable * v0 = new Variable();   // Here the same.  
    v->ini = n;
    n->father = v;

    Table * t = new Table();
    t->variables[0] = v;

    v0 = t->variables[0];

    cout << *(static_cast<float *>(v0->ini->get_value())) << endl;
}

如何不改变地存储指针中的值?看来我应该使用 const 或类似的东西,但我不知道如何使用。将字段值声明为私有没有帮助。想法是稍后用 void * 替换值,以存储基本日期的任何国王,而不仅仅是浮点数据。

谢谢!

这看起来不对:

void Nodo::set_value(float m)
{
    float * r = new float();
    r = &m;
    value = (float *)r;
}

r 被分配给 m 的指针是临时的,一旦 set_value 完成,该指针将失效。你也覆盖了 r 值,所以你在这里有泄漏。正确的版本是:

void Nodo::set_value(float m)
{
    float * r = new float();
    *r = m;
    value = r;
}

顺便说一句。我没有深入研究您的代码,...