C ++ const数组没有理由改变

时间:2017-10-25 09:04:09

标签: c++

我遇到一段代码问题。我将为您提供简化版本:

class AdvancedImage
{
    Image *_source;
    int _w;
    int _h;

    AdvancedImage(const Image *src, const PointFloat corners[], int w, int h)
    {
        InitializeInstanceFields();
        _source = new Image(src->data, src->h, src->w);
        _w = w;
        _h = h;

        PointFloat newPoints[4];
        for (int i = 0; i < 4; i++)
        {
            newPoints[i] = corners[i];
        }

        /* Initialisation continue... */
    }

    InitializeInstanceFields()
    {
        _w = 0;
        _h = 0;
    }
}

class Image
{
    unsigned char *data;
    int width;
    int height;
    int size;

    Image(const unsigned char newData[], int h, int w)
    {
        InitializeInstanceFields();
        this->height = h;
        this->width = w;
        this->size = h * w;
        this->data = new unsigned char[this->size];
        for (int i = 0; i < this->size; i++)
        {
            this->data[i] = newData[i];
        }
    }
}

class PointFloat
{
    float X;
    float Y;

    PointFloat(float x, float y)
    {
        this->X = x;
        this->Y = y;
    }
}

我正在使用这样的AdvancedImage

void myFunction (const Image *img, const PointFloat corners[])
{
    AdvancedImage *advImg = 0;
    /* Some code */
    advImg = new AdvancedImage(img, corners, 15, 30);
    /* Code continue */
}

我的问题是cornersnew AdvancedImage中的值发生了变化。我尝试调试,我看到了一些我无法解释的东西。在构造函数AdvancedImage中,corner [0]为{76.0,45.0}。我向&corners添加了一个监视,在构造函数new Image中值不会改变,但是当代码从构造函数返回时(转到行_w = w;),值现在类似于{7.7877970e40,0.2554460 E-20}。

我找了一个解决方案,但什么也没做。我怎么解决这个问题 ?哪里可以来自?

0 个答案:

没有答案