运算符和副本构造函数的重载
Overload of operators and constructor of copy
C++ 需要创建副本的构造函数以将一个实例分配给另一个实例。例如:
my_class a = b;
如果我暗示复制是错误的,因为它用作地址分配。因此,如果我更改 a
,b
也会更改。所以,我应该创建副本的构造函数:
my_class(const my_class &obj);
这似乎是显而易见的事情,其余的不言而喻,但是当我发现重载运算符时,我产生了疑问:
my_class operator=(my_class obj);
事实证明,我可以将它用作赋值,而不必使用副本的构造函数。那正确吗?但是,为什么放置在 operator=
定义中的赋值作为复制工作。
你可以使用 or 复制赋值,以及复制的构造函数。
class A {
A(const A& a);
A& operator=(const A& a);
};
A a1;
A a2(a1); // calling constructor of copies A(const A& a);
A a2 = a1; // also calling constructor of copies A(const A& a);
A a3;
a3 = a1; // calling copy assignment operator=(const A& a);
下面是示例实现:
class A
{
public:
int* x;
A(int data)
{
this->x = new int(data);
}
A(const A& a)
{
this->operator=(a);
}
A& operator=(const A& a)
{
this->x = new int(*a.x);
return *this;
}
};
您还可以提供特殊检查以避免自我分配,例如if (a != this)
C++ 需要创建副本的构造函数以将一个实例分配给另一个实例。例如:
my_class a = b;
如果我暗示复制是错误的,因为它用作地址分配。因此,如果我更改 a
,b
也会更改。所以,我应该创建副本的构造函数:
my_class(const my_class &obj);
这似乎是显而易见的事情,其余的不言而喻,但是当我发现重载运算符时,我产生了疑问:
my_class operator=(my_class obj);
事实证明,我可以将它用作赋值,而不必使用副本的构造函数。那正确吗?但是,为什么放置在 operator=
定义中的赋值作为复制工作。
你可以使用 or 复制赋值,以及复制的构造函数。
class A {
A(const A& a);
A& operator=(const A& a);
};
A a1;
A a2(a1); // calling constructor of copies A(const A& a);
A a2 = a1; // also calling constructor of copies A(const A& a);
A a3;
a3 = a1; // calling copy assignment operator=(const A& a);
下面是示例实现:
class A
{
public:
int* x;
A(int data)
{
this->x = new int(data);
}
A(const A& a)
{
this->operator=(a);
}
A& operator=(const A& a)
{
this->x = new int(*a.x);
return *this;
}
};
您还可以提供特殊检查以避免自我分配,例如if (a != this)