使用公共命名方法实现非公共赋值运算符

Implementing a non-public assignment operator with a public named method?

本文关键字:实现 赋值运算符 方法      更新时间:2023-10-16

它应该复制一个动画精灵。我有第二个想法,它有改变*this对象的不幸副作用。

如何在没有副作用的情况下实现此功能?

编辑:

根据新的答案,问题实际上应该是:如何使用公共命名方法实现非公共赋值运算符而没有副作用?(更改了标题)。

public:
AnimatedSprite& AnimatedSprite::Clone(const AnimatedSprite& animatedSprite) {
    return (*this = animatedSprite);
}
protected:
AnimatedSprite& AnimatedSprite::operator=(const AnimatedSprite& rhs) {
    if(this == &rhs) return *this;
    destroy_bitmap(this->_frameImage);
    this->_frameImage = create_bitmap(rhs._frameImage->w, rhs._frameImage->h);
    clear_bitmap(this->_frameImage);
    this->_frameDimensions = rhs._frameDimensions;
    this->CalcCenterFrame();
    this->_frameRate = rhs._frameRate;
    if(rhs._animation != nullptr) {
        delete this->_animation;
        this->_animation = new a2de::AnimationHandler(*rhs._animation);
    } else {
        delete this->_animation;
        this->_animation = nullptr;
    }
    return *this;
}

您可以调用私有赋值运算符:

public:
AnimatedSprite& AnimatedSprite::Clone(const AnimatedSprite& animatedSprite) {
    return ( operator=(animatedSprite));
}

如果您尝试进行分配,则无法绕过修改this

通常,clone 会返回指向新实例的指针或智能指针:

struct IFoo {
  virtual IFoo* clone() const = 0;
};
struct Foo1 : public virtual IFoo {
  virtual IFoo* clone() { return new Foo1(this);}
};
struct Foo2 : public virtual IFoo {
  virtual IFoo* clone() { return new Foo2(this);}
};
IFoo* foo0 = new Foo1();
...
IFoo* fooClone = foo0.clone();

  1. 克隆不应该有参数,因为它应该克隆自己。如果你想改变*这个你有运算符=。
  2. 尝试返回值。如果返回创建临时对象,则编译器可以对其进行优化以在没有 temp 的情况下构造新对象。

    AnimatedSprite AnimatedSprite::Clone() { 返回动画精灵(*这个);}

    AnimatedSprite clone = someObject.Clone();//不会导致创建临时对象

//编辑

所以你需要这样的东西吗?我也不确定,为什么你需要返回参考。

public:
AnimatedSprite& AnimatedSprite::CopyTo(AnimatedSprite& animatedSprite) {
    animatedSprite = *this;
    return *this;
}
AnimatedSprite& AnimatedSprite::CopyFrom(AnimatedSprite& animatedSprite) {
    return (*this = animatedSprite);
}