gpt4 book ai didi

c++ - 使用公共(public)命名方法实现非公共(public)赋值运算符?

转载 作者:行者123 更新时间:2023-11-28 08:01:34 24 4
gpt4 key购买 nike

它应该复制一个 AnimatedSprite。我重新考虑它具有更改 *this 对象的不幸副作用。

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

编辑:

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

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

最佳答案

您可以调用私有(private)分配运算符(operator):

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

<罢工>

关于c++ - 使用公共(public)命名方法实现非公共(public)赋值运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11334449/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com