c++重写运算符和this

c++ override operator and this

本文关键字:this 运算符 重写 c++      更新时间:2023-10-16

我想重写"="运算符,但我遇到了一个问题,该类有一个const成员,我想在使用"="时更改它,我认为解构对象并构造一个新对象可能可行,但"this"不能更改。所以,你能帮我吗?

您可以标记要更改mutable的成员。这就是关键字的用途。

当然,您可能违反了对类用户的隐含约定,即operator=不会修改类。。。

您可以使用pimpl习语。例如:

class Foo_impl
{
public:
    Foo(int x, int y, int z)
        :x_(x), y_(y), z_(z)
    {}
    const int x_;
    int y_,z_;
};
class Foo
{
public:
    Foo(int x, int y, int z)
        :impl_(new Foo_impl(x,y,z))
    {}    
    Foo & operator=(Foo rhs)
    {
        swap(rhs);
        return *this;
    }
    void swap(Foo & rhs)
    {
        std::swap(impl_, rhs.impl_);
    }
    // still need copy constructor
private:
    std::unique_ptr<Foo_impl> impl_;
};

我真的不明白这有什么意义。