修改const参数引用

时间:2013-05-27 07:27:25

标签: c++ c++11

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

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并且这是有意义的但是我需要一种方法来使用Item I的SetParent,而不会失去构建我的能力,因为:

Box B(Item());

而不是:

Item I;
Box B(I);

任何想法如何通过调用SetParent来修改它的同时保持I的内联构造?

1 个答案:

答案 0 :(得分:2)

解决方案是将Parent成员声明为可变并使SetParent方法保持不变。示例代码如下并且可用online

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;
}