在 C++ 中,我们什么时候需要编写自己的赋值运算符?
这里我们将了解在 C++ 中何时需要创建自己的赋值运算符。如果一个类没有任何指针,那么我们不需要创建赋值运算符和复制构造函数。C++ 编译器为每个类创建复制构造函数和赋值运算符。如果这些运算符不够用,那么我们就必须创建自己的赋值运算符。
示例
#include<iostream>
using namespace std;
class MyClass { //no user defined assignment operator or copy constructor is present
int *ptr;
public:
MyClass (int x = 0) {
ptr = new int(x);
}
void setValue (int x) {
*ptr = x;
}
void print() {
cout << *ptr << endl;
}
};
main() {
MyClass ob1(50);
MyClass ob2;
ob2 = ob1;
ob1.setValue(100);
ob2.print();
}输出
100
在 main() 函数中,我们使用 setValue() 方法为 ob1 设置了 x 的值。该值也反映在对象 ob2 中;这种意外的变化可能会产生一些问题。没有用户定义的赋值运算符,因此编译器会创建一个。这里它将 RHS 的 ptr 复制到 LHS。因此,这两个指针都指向同一个位置。
为了解决这个问题,我们可以采用两种方法。我们可以创建一个虚拟的私有赋值运算符来限制对象的复制,或者创建我们自己的赋值运算符。
示例
#include<iostream>
using namespace std;
class MyClass { //no user defined assignment operator or copy constructor is present
int *ptr;
public:
MyClass (int x = 0) {
ptr = new int(x);
}
void setValue (int x) {
*ptr = x;
}
void print() {
cout << *ptr << endl;
}
MyClass &operator=(const MyClass &ob2) {
// Check for self assignment
if(this != &ob2)
*ptr = *(ob2.ptr);
return *this;
}
};
main() {
MyClass ob1(50);
MyClass ob2;
ob2 = ob1;
ob1.setValue(100);
ob2.print();
}输出
50
这里赋值运算符用于创建深拷贝并存储单独的指针。有一点我们必须牢记。我们必须检查自引用,否则赋值运算符可能会更改当前对象的值。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP