侯捷C++复现:一个带有指针的string类

目录

三大件

1.复制拷贝函数

2.复制构造函数

3.析构函数


三大件

带有指针的类要注意三大件:

1.复制拷贝函数

其中复制拷贝函数是在已有对象的基础上,修改指针。实现上是重载=操作符,这里要注意的细节就是检查自我赋值。

2.复制构造函数

这是在没有对象的基础上,用另外一个相同的对象来构造一个新的对象,所以只需要为指针创建新的空间就行。

3.析构函数

释放指针对应的空间哒!

具体的测试和类的代码如下所示:

类:

//
// Created by 浅笑 on 2022/11/27.
//
#include <cstring>
#include <iostream>
#ifndef CLION_PJ_MY_STRING_H
#define CLION_PJ_MY_STRING_H
class my_string{
public:
    my_string(const char *cstr=0);
    // 拷贝构造 还未存在对象
    my_string(const my_string& str);
    // 拷贝赋值 已经存在对象
    my_string& operator=(const my_string& str);
    char *get_cstr() const {return m_data;}
    // 析构函数
    ~my_string();
private:
    char *m_data;
};

my_string::my_string(const char *cstr) {
    std::cout<<"common constructor"<<std::endl;
    if (cstr){
        m_data=new char [strlen(cstr)+1];
        strcpy(m_data,cstr);
    }else{
        m_data=new char [1];
        *m_data='\0';
    }
}

my_string::my_string(const my_string &str) {
    std::cout<<"copy constructor"<<std::endl;
    m_data=new char [strlen(str.m_data)+1];
    strcpy(m_data, str.m_data);
}

my_string& my_string::operator=(const my_string &str) {
    std::cout<<"copy ="<<std::endl;
    // 检查是否是自己给自己赋值
    if (this==&str){
        return *this;
    }
    delete [] m_data;
    m_data=new char [strlen(str.m_data)+1];
    strcpy(m_data, str.m_data);
    return *this;
}

my_string::~my_string() {
    delete [] m_data;
}

// 重载输出
std::ostream& operator<<(std::ostream &os, const my_string& str){
    return os<<str.get_cstr();
}

#endif //CLION_PJ_MY_STRING_H

测试:

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<ctime>
#include<vector>
#include<algorithm>
#include<cstring>
#include<set>
#include<map>
#include<queue>
#include<string>
#include "my_string.h"

using namespace std;

int main()
{
    my_string str1("Kobe Bryant");
    my_string str2(str1);
    my_string str3=str1;
    my_string str4("lyt");
    str4=str1;
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值