String类的简单构造

摘自高质量C++编程指南

class String
{
public:
    String(const char*str=NULL);   //普通构造函数
    String(const String &other);    //拷贝构造函数
    ~String(void);                     //析构函数
    String & operate = (const String &other);   //赋值函数
private:
    char *m_data;                       //字符串
};
String::~String(void)
{
    delete [] m_data;
}
String::String(const char *str) //构造函数是一种特殊的类成员函数,是当创建一个类的对象时,它被调用来对类的数据成员进行初始化和分配内存
{
    if(str==NULL)
    {
        m_data=new char [1];
        *mdata='\0';
    }
    else
    {
        int length=strlen(str);
        m_data=new char[length+1];   //不算'\0'
        strcpy(m_data,str);
    }
}
String::String(const String &other) //拷贝构造函数是C++独有的,它是一种特殊的构造函数,用基于同一类的一个对象构造和初始化另一个对象。
{
    int length=strlen(other.m_data);
    m_data=new char[length+1];
    strcpy(m_data,other.m_data);
}
String &String::operate =(const String &other)  //当一个类的对象向该类的另一个对象赋值时,就会用到该类的赋值函数。
{
    if(this==&other)
        return *this;
    delete [] m_data;
    int length=strlen(other.m_data);
    m_data=new char[length+1];
    strcpy(m_data,other.m_data);
    return *this;
}
在C++中,`string` 是标准库中的一个非常重要的,它提供了一系列方法来处理字符串数据。在实际的开发中,我们一般使用标准库中的 `std::string`,但是理解其基本实现方式有助于我们更好地理解字符串对象是如何工作的。 下面是一个简单的 `string` 的实现,用于演示其基本结构和功能: ```cpp #include <iostream> #include <cstring> class SimpleString { private: char* data; // 指向字符串数据的指针 size_t length; // 字符串的长度 public: // 构造函数 SimpleString(const char* str = "") : length(strlen(str)) { data = new char[length + 1]; strcpy(data, str); } // 拷贝构造函数 SimpleString(const SimpleString& other) : length(other.length) { data = new char[length + 1]; strcpy(data, other.data); } // 赋值操作符重载 SimpleString& operator=(const SimpleString& other) { if (this != &other) { delete[] data; // 释放旧数据 length = other.length; data = new char[length + 1]; strcpy(data, other.data); } return *this; } // 析构函数 ~SimpleString() { delete[] data; } // 获取字符串长度 size_t getLength() const { return length; } // 重载[]操作符,用于访问字符 char& operator[](size_t index) { return data[index]; } // 重载=操作符,用于赋值字符串 SimpleString& operator=(const char* str) { delete[] data; length = strlen(str); data = new char[length + 1]; strcpy(data, str); return *this; } // 输出字符串 friend std::ostream& operator<<(std::ostream& os, const SimpleString& str) { os << str.data; return os; } }; int main() { SimpleString s1("Hello"); SimpleString s2 = s1; // 拷贝构造 s1 = "World"; // 赋值操作 std::cout << s1 << std::endl; // 输出: World std::cout << s2 << std::endl; // 输出: Hello return 0; } ``` 上述代码展示了如何实现一个简单的字符串,包含基本的构造、拷贝构造、赋值操作符重载、析构函数,以及一些基本操作如获取字符串长度和重载 `[]` 和 `=` 操作符。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值