将数据从构造函数传输回调用方法时更改数据成员

Data member changing while transferring the data back from the constructor to the calling method

本文关键字:方法 数据成员 调用 回调 数据 构造函数 传输      更新时间:2023-10-16

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

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中的垃圾。我知道这是一个 c'tor 问题,因为当我添加新矩形时不会发生这种情况。

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

该参数称为 chIn ,但您改为使用自身初始化成员ch

这会导致其未指定的预初始化值。

我想你的意思是写:

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

这里ch是什么?看来你的意思是chIn.