c++重写运算符和this
c++ override operator and this
我想重写"="运算符,但我遇到了一个问题,该类有一个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_;
};
我真的不明白这有什么意义。
相关文章:
- 运算符++();调用和++(*this)有什么区别?
- 为什么在通过引用返回运算符分配时取消引用'this'指针?
- 如何在"this"上调用运算符()?
- 从 std::ostream 重载 << 运算符时,为什么编译器会给出"too many parameters for this operator function"错误?
- 当取消引用运算符 (*) 重载时,*this 的使用是否受到影响?
- C++指针上的关键字运算符"this"
- 假设我有作业运算符,我的复制构造函数是this = obj可以
- 为什么我的重载运算符+在向自身添加变量时会在返回时使"this"未初始化?
- "return *this"赋值运算符重载
- 是否可以在实例方法中使用带有"this"的重载运算符?
- 重载 = 运算符时如何使用 THIS 指针
- 运算符+=可以调用自己,但"*this"与"rhs"交换吗?
- 可能的分段错误:是否正确使用了"this->"运算符?
- 使用 This 关键字和运算符重载
- 在运算符中使用“this”
- 由 sf::P acket 定义的运算符<<是否与 sf::P acket 派生类的 (*this) 一起工作?
- 运算符this的c++重载
- c++重写运算符和this
- 我可以在运算符=中使用placement new(this)吗
- 重载类函数中的按位和 (&) 运算符和"*this"