CUDA版本与PyTorch对应关系表(Miniconda安装参考)
2025/12/30 15:26:25
题目:
实现自定义String类中的成员函数
class MyString { public: MyString(const char* str = nullptr); MyString(const MyString& other); MyString& operator=(const MyString& other); ~MyString(); private: char* _str; size_t _length; };重点:
1.深拷贝
2.拷贝赋值运算符要处理自赋值
// 1. 带默认参数的构造函数实现 MyString::MyString(const char* str) : _length(0) { if (str == nullptr) { _str = new char[1]; _str[0] = '\0'; } else { _length = strlen(str); _str = new char[_length + 1]; strcpy(_str, str); } } // 2. 拷贝构造函数实现 MyString::MyString(const MyString& other) { _length = other._length; _str = new char[_length + 1]; strcpy(_str, other._str); } // 3. 拷贝赋值运算符重载实现 MyString& MyString::operator=(const MyString& other) { // 处理自赋值 if (this == &other) { return *this; } // 释放当前对象已有内存 delete[] _str; // 深拷贝 _length = other._length; _str = new char[_length + 1]; strcpy(_str, other._str); // 返回当前对象引用 return *this; } // 4. 析构函数实现 MyString::~MyString() { delete[] _str; _str = nullptr; }