程序设计二(面向对象)_实训7_赋值运算符重载
时间: 2024-01-08 07:49:20 浏览: 34
赋值运算符重载是指为一个类定义一个赋值运算符,以实现在对象间赋值的操作。在 C++ 中,赋值运算符重载函数的函数名必须为 operator=,其格式如下:
```
class_name& operator=(const class_name& rhs){
//实现赋值操作
return *this;
}
```
其中,class_name 为类名,rhs 为右操作数,即赋值号右侧的值。重载赋值运算符函数必须返回一个指向当前对象的引用,以支持链式赋值操作。
下面是一个实现自定义类的赋值运算符重载的例子:
```c++
#include <iostream>
using namespace std;
class MyString {
public:
MyString() : buffer(NULL), size(0) {
}
MyString(const char* input) {
if (input != NULL) {
size = strlen(input);
buffer = new char[size + 1];
strcpy(buffer, input);
} else {
buffer = NULL;
size = 0;
}
}
MyString(const MyString& copySource) {
if (copySource.buffer != NULL) {
size = copySource.size;
buffer = new char[size + 1];
strcpy(buffer, copySource.buffer);
} else {
buffer = NULL;
size = 0;
}
}
~MyString() {
if (buffer != NULL) {
delete[] buffer;
buffer = NULL;
size = 0;
}
}
MyString& operator=(const MyString& copySource) {
if ((this != ©Source) && (copySource.buffer != NULL)) {
if (buffer != NULL) {
delete[] buffer;
}
size = copySource.size;
buffer = new char[size + 1];
strcpy(buffer, copySource.buffer);
}
return *this;
}
int GetLength() const {
return size;
}
const char* GetString() const {
return buffer;
}
private:
char* buffer;
unsigned int size;
};
int main() {
MyString str1("Hello");
MyString str2("World");
str2 = str1;
cout << str2.GetString() << endl;
return 0;
}
```
在上面的例子中,MyString 类重载了赋值运算符=,实现了一个深拷贝的操作。当赋值号左右两侧的对象不相同时,才进行赋值操作。同时,在进行赋值操作前,会先释放已有的 buffer,再根据源字符串的长度重新分配内存。
运行结果为:
```
Hello
```