我有一个类,它有几个 int 和一个定义了构造函数的 const int 成员。
class SomeContainer
{
public:
SomeContainer():
member1(0),
member2(staticMethod())
{}
private:
static int staticMethod();
int member1;
const int member2;
}
我需要创建一个赋值运算符,因为我在另一个类 MainClass 和代码中使用了这个类
MainClass* p1;
MainClass* p2
{
//...
*p1 = *p2 // fails since SomeContainer doesn't have copy assignment operator
}
这段代码是否足够了,还是我遗漏了什么?
{
SomeContainer(const SomeContainer& other): // copy ctor
member1(other.member1),
member2(other.member2)
{}
SomeContainer& operator=(const SomeContainer& other) // assignment operator
{
member1 = other.member1;
}
}
移动构造函数和移动赋值呢?我是否也需要实现这些?
最佳答案
首先,如果 p1
和 p2
是指针,那么您可以直接分配它们。
如果移动构造函数不存在,则将使用复制构造函数。
我仍然很难理解允许对具有常量非静态部分的事物进行赋值的逻辑含义。
关于c++ - 使用 int 成员实现哪些运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22670354/