数据成员在将数据从构造函数传回调用方法时发生更改 [英] Data member changing while transferring the data back from the constructor to the calling method

查看:123
本文介绍了数据成员在将数据从构造函数传回调用方法时发生更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我反序列化对象时,我的Square构造函数将我的 ch 的值更改为未知的值。我不明白为什么。

When I deserialize an object my Square constructor changes the value of my ch to something unknown. I can't understand why.

bool Palette::addShape(int shape, fstream &input)
{
    int x, y, len;
    double shiftX, shiftY;
    char ch;

    input >> x >> y >> len >> ch;
    Shape *toAdd;
    std::list<Shape *>::iterator itr;

    switch (shape)
    {
    case RectangleID:
        toAdd = new Rectangle(x, y, len, ch);
        palette.emplace_back(toAdd);
        break;
    case SquareID:
        toAdd = new Square(x, y, len, ch);
        palette.emplace_back(toAdd);
        break;
    }

    return true;
}

这是构造函数:

Square(int x, int y, int length, char chIn) : Shape(x, y, length, ch)
{
    shapeId = SquareID;
}

当我调试构造函数时,我看到它获得正确的值,我在构造函数返回之后检查 toAdd 的值,看到 ch 中的垃圾。我知道这是一个问题,因为它不会发生,当我添加一个新的矩形。

When I debug the constructor I see that it gets the right values, but when I check the value of toAdd after the constructor returns I see the junk in ch. I know it's a c'tor problem since it does not happen when I add a new Rectangle.

推荐答案


Square(int x, int y, int length, char chIn) : Shape(x, y, length, ch)
//                                    ^^^^                        ^^


此参数称为 chIn ,但是你自己初始化了成员 ch

The parameter is called chIn, but you initialised the member ch with itself instead.

这会导致其未指定,初始值。

This results in its unspecified, pre-initialisation value.

我想你是要写:

 Square(int x, int y, int length, char chIn) : Shape(x, y, length, chIn)
 //                                                                ^^^^

这篇关于数据成员在将数据从构造函数传回调用方法时发生更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆