您的位置:首页 > 游戏 > 游戏 > 温州网站设计只找亿企邦_深圳好客站seo_seo教学平台_宁波优化推广找哪家

温州网站设计只找亿企邦_深圳好客站seo_seo教学平台_宁波优化推广找哪家

2024/10/5 17:19:24 来源:https://blog.csdn.net/2301_78756095/article/details/142466649  浏览:    关键词:温州网站设计只找亿企邦_深圳好客站seo_seo教学平台_宁波优化推广找哪家
温州网站设计只找亿企邦_深圳好客站seo_seo教学平台_宁波优化推广找哪家

头文件
// My_string.h
#ifndef MY_STRING_H
#define MY_STRING_H#include <cstring>
#include <algorithm>class My_string {
private:char* data;size_t length;void resize(size_t new_length) {size_t new_capacity = std::max(new_length + 1, length);char* new_data = new char[new_capacity];std::copy(data, data + length, new_data);delete[] data;data = new_data;}public:// 默认构造函数My_string() : data(new char[1]), length(0) {data[0] = '\0';}// 构造函数My_string(const char* str);// 拷贝构造函数My_string(const My_string& other);// 移动构造函数My_string(My_string&& other) noexcept;// 赋值操作符My_string& operator=(const My_string& other);// 移动赋值操作符My_string& operator=(My_string&& other) noexcept;// 析构函数~My_string();// 字符串连接My_string& operator+=(const My_string& other);// 获取字符串长度size_t size() const;// 获取C风格字符串const char* c_str() const;// 打印字符串void print() const;
};#endif // MY_STRING_H

函数体

 

cpp

// My_string.cpp
#include "My_string.h"
#include <iostream>// 构造函数
My_string::My_string(const char* str) {if (str) {length = std::strlen(str);data = new char[length + 1];std::strcpy(data, str);} else {data = new char[1];length = 0;data[0] = '\0';}
}// 拷贝构造函数
My_string::My_string(const My_string& other) : length(other.length), data(new char[other.length + 1]) {std::strcpy(data, other.data);
}// 移动构造函数
My_string::My_string(My_string&& other) noexcept : data(other.data), length(other.length) {other.data = nullptr;other.length = 0;
}// 赋值操作符
My_string& My_string::operator=(const My_string& other) {if (this != &other) {delete[] data;length = other.length;data = new char[length + 1];std::strcpy(data, other.data);}return *this;
}// 移动赋值操作符
My_string& My_string::operator=(My_string&& other) noexcept {if (this != &other) {delete[] data;data = other.data;length = other.length;other.data = nullptr;other.length = 0;}return *this;
}// 析构函数
My_string::~My_string() {delete[] data;
}// 字符串连接
My_string& My_string::operator+=(const My_string& other) {size_t new_length = length + other.length;resize(new_length);std::strcpy(data + length, other.data);length = new_length;return *this;
}// 获取字符串长度
size_t My_string::size() const {return length;
}// 获取C风格字符串
const char* My_string::c_str() const {return data;
}// 打印字符串
void My_string::print() const {std::cout << data << std::endl;
}

主函数

 

cpp

// main.cpp
#include "My_string.h"int main() {My_string s1("Hello");My_string s2 = s1; // 调用拷贝构造函数My_string s3;s3 = s1; // 调用赋值操作符My_string s4(std::move(s1)); // 调用移动构造函数s2 += s3;s2.print(); // 输出: HelloHelloreturn 0;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com