1

好的,所以我有两个看起来像的类:

class Item
{
    private:
        HANDLE Parent;

    public:
        Item(const Item &I) = delete;
        Item(Item &&I) = delete;
        void SetParent(HANDLE Handle);

        Item& operator = (const Item &I) = delete;
        Item& operator = (Item &&I);
};

void Item::SetParent(HANDLE Handle)
{
    this->Parent = Handle;
}

Item& Item::operator = (Item&& I) {/*Do Move Here*/}


class Box
{
    private:
        HANDLE Handle;

    public:
        void Add(const Item &I);
};

void Box::Add(const Item &I)
{
    I.SetParent(this->Handle);   //Error.. Item I is const.
}

我得到了我是 const 的错误,这是有道理的,但我需要一种方法来 SetParent 的 Item I 而不会失去构建 I 的能力,如下所示:

Box B(Item());

代替:

Item I;
Box B(I);

有什么想法可以在通过调用 SetParent 对其进行修改的同时保持 I 的内联构造吗?

4

1 回答 1

2

一种解决方案是将Parent成员声明为可变的并使SetParent方法保持不变。示例代码如下,可在线获取

typedef int HANDLE;

class Item
{
    private:
        mutable HANDLE Parent;

    public:
        Item(const Item &I) = delete;
        Item(Item &&I) = delete;
        void SetParent(HANDLE Handle) const;

        Item& operator = (const Item &I) = delete;
        Item& operator = (Item &&I);
};

void Item::SetParent(HANDLE Handle) const
{
    this->Parent = Handle;
}

class Box
{
    private:
        HANDLE Handle;

    public:
        void Add(const Item &I);
    public:
         Box(const Item &I) {
            Add(I);
         }
};

void Box::Add(const Item &I)
{
    I.SetParent(this->Handle);   //Error.. Item I is const.
}

int main(void) {
    return 0;
}
于 2013-05-27T07:48:23.587 回答