使用公共命名方法实现非公共赋值运算符
Implementing a non-public assignment operator with a public named method?
它应该复制一个动画精灵。我有第二个想法,它有改变*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();
- 克隆不应该有参数,因为它应该克隆自己。如果你想改变*这个你有运算符=。
-
尝试返回值。如果返回创建临时对象,则编译器可以对其进行优化以在没有 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);
}
相关文章:
- 重载Singly Linked List中的赋值运算符
- 使用赋值运算符重载从类中返回jobject
- 标准库类型的赋值运算符的引用限定符
- 默认赋值运算符如何在实际 STL 中实现
- 复制构造函数和赋值运算符的值类实现
- 将赋值运算符实现为"destroy + construct"是否合法?
- 如何在模板容器类中实现复制构造函数和赋值运算符
- 如何为具有自引用指针的类实现复制构造函数/赋值运算符
- 使用shared_ptr时需要实现析构函数、复制构造函数、赋值运算符
- 如何实现赋值运算符,使多个实例共享公共数据
- 如何使用继承(抽象基类)实现移动构造函数和移动赋值运算符
- { } 构造函数实现中的赋值运算符 => 错误
- 模板的赋值运算符(成员函数)实现的正确语法
- 使用公共命名方法实现非公共赋值运算符
- 复制构造函数和赋值运算符实现选项 -
- 在什么场景中,我应该明确需要实现移动构造函数和移动赋值运算符
- 在 C++98 中实现移动构造函数和移动赋值运算符以获得更好的性能
- 在二维数组上实现move赋值运算符
- 右值中的代理类-如何实现赋值运算符
- GCC 4.7.2 对shared_ptr(模板化)赋值运算符的实现是否存在错误?