0

AnimatedSpriteをコピーすることになっています。*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;
}
4

2 に答える 2

1

プライベート代入演算子を呼び出すことができます:

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();

于 2012-07-04T19:26:03.560 に答える
0
  1. クローンにはパラメータを設定しないでください。クローン自体を作成する必要があります。*これを変更したい場合は、演算子=があります。
  2. 値を返してみてください。代わりに一時オブジェクトを作成する場合は、コンパイラによって最適化されて、一時オブジェクトがなくても新しいオブジェクトを作成できます。

    AnimatedSprite AnimatedSprite :: Clone(){return AnimatedSprite(* this); }

    AnimatedSprite clone = someObject.Clone(); //一時オブジェクトの作成にはつながりません

//編集

だからあなたはこのようなものが必要ですか?また、なぜ参照を返す必要があるのか​​わかりません。

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

AnimatedSprite& AnimatedSprite::CopyFrom(AnimatedSprite& animatedSprite) {
    return (*this = animatedSprite);
}
于 2012-07-04T19:32:58.857 に答える