#include <iostream>
#include <cstring>
using namespace std;
class mystring
{
private:
char *str; // 记录c风格的字符串
int size; // 记录字符串的实际长度
public:
// 无参构造
mystring():size(10)
{
str = new char[size];
str[0] = '\0';
}
// 有参构造
mystring(const char *s)
{
size = strlen(s);
//多一位存'\0'
str = new char[size+1];
strcpy(str,s);
}
// 拷贝构造
mystring(const mystring & other)
{
size = other.size;
str = new char[size+1];
strcpy(str, other.str);
}
// 拷贝赋值
mystring & operator= (const mystring & other)
{
if(this != &other)
{
size = other.size;
//上一个str中空间不能保证能够存储赋值后的字符串
//需要delete旧空间,创建新空间
delete[] str;
str = new char[size+1];
strcpy(str, other.str);
}
//如果右值等于左值,不做赋值处理
return *this;
}
// 析构函数
~mystring()
{
delete[] str;
}
// 判空函数:返回值为bool类型
//返回值为ture则为空,返回值为false,则不空
bool empty()
{
if(strlen(str) == 0)
return true;
else
return false;
}
// size函数
int mysize()
{
return size;
}
// c_str函数:将C++风格字符串转换为C风格字符串
char* c_str()
{
return str;
}
// at函数:数组下标越界,就会抛出异常
char &at(int pos)
{
//判断下标合法
if(pos < 0 || pos >= size)
{
cout << "下标不合法" << endl;
}
return str[pos];
}
};
int main()
{
mystring s1;
cout << "无参构造sizeof(s1) = " << s1.mysize() << endl;
cout << "无参构造s1初始化后判空:" << boolalpha << s1.empty() << endl;
mystring s2("hello world");
cout << "有参构造s2 = " << s2.c_str() << endl;
mystring s3 = s2;
cout << "拷贝构造s3 = " << s3.c_str() << endl;
s1 = s2;
cout << "赋值构造s1 = " << s1.c_str() << endl;
cout << "无参构造s1赋值后判空:" << s1.empty() << endl;
s1.at(6) = 'W';
cout << "s1 = " << s1.c_str() << endl;
return 0;
}
C++day1
最新推荐文章于 2024-08-16 23:08:36 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)