String类的赋值运算符重载
(1)https://zh.cppreference.com/w/%E9%A6%96%E9%A1%B5
(2)String类提供了=和+等多个运算符重载函数的成员
(3)标准库只给了API,没给实现,咱们可以自己实现个=运算符重载函数
String的=运算符重载演练
(1)自己编写一个MyString类,成员变量char *pBuf指向实际存储字符串的buf,new动态内存来使用。
(2)实践:先完成构造函数,成员函数print,len等基础设计,写
#include <cstring>
#include <iostream>
class MyString {
private:
char *pBuf; //指针指向实际存储buffer空间,采用动态分配
int cnt; //记录buffer中有效字符的长度
public:
// 默认构造函数
MyString() : pBuf(nullptr) {}
// 带参数的构造函数
MyString(const char *str) {
cnt = strlen(str);
if (str) {
pBuf = new char[cnt + 1];
strcpy(pBuf, str);
} else {
pBuf = nullptr;
}
}
// 拷贝构造函数,深拷贝
MyString(const MyString &other) {
cnt = strlen(other.pBuf);
if (other.pBuf) {
pBuf = new char[cnt + 1]; //申请空间
strcpy(pBuf, other.pBuf); //赋值
} else {
pBuf = nullptr;
}
}
// 重载 = 运算符,深拷贝
MyString &operator=(const MyString &other) {
std::cout << "重载 = 运算符,深拷贝" << std::endl;
cnt = strlen(other.pBuf);
if (this != &other) { // 避免自赋值
delete[] pBuf; // 释放旧的内存
if (other.pBuf) {
pBuf = new char[cnt + 1];//申请空间
strcpy(pBuf, other.pBuf);//拷贝内容
} else {
pBuf = nullptr;
}
}
return *this;
}
// 析构函数
~MyString() { delete[] pBuf; }
// 打印函数
void print() const {
if (pBuf) {
std::cout << "cnt:" << cnt << std::endl;
std::cout << pBuf << std::endl;
} else {
std::cout << "Empty string" << std::endl;
}
}
// 获取字符串长度函数
int len() const { return pBuf ? strlen(pBuf) : 0; }
};
int test070301() {
MyString str1("Hello, World!");
str1.print();
std::cout << "--------1---------" << std::endl;
MyString str2;
str2.print();
std::cout << "-------2----------" << std::endl;
str2 = str1;//重载 = 运算符,深拷贝
str2.print();
std::cout << "-------3----------" << std::endl;
MyString str3(str1);
str3.print();
std::cout << "-------4----------" << std::endl;
return 0;
}
总结
不管是拷贝构造函数还是运算符重载,都要注意内存管理
参考:
https://zh.cppreference.com/w/%E9%A6%96%E9%A1%B5
学习记录,侵权联系删除。
来源:朱老师物联网大课堂