c++ 类的构造和析构

myString.h

#ifndef MYSTRING_H
#define MYSTRING_H
class myString
{
public:
    myString(const char * s=nullptr);
    myString(const myString & another);//deep 拷贝
    myString& operator=(const myString & another);//赋值 拷贝
    void dis();
    ~myString();
private:
    char *str_;
};
#endif // MYSTRING_H
#include "myString.h"
#include <iostream>
#include <string.h>
int k=1;//构造次数
int kk=1;//析构次数
int cpys=1;//deep 拷贝次数
myString::myString(const char * s)
{
    if(s==nullptr)
    {
        str_=new char[1];//空串
        *str_='\0';
        std::cout<<"空串"<<std::endl;
    }else
    {
        int len=strlen(s)+1;//非空串
        str_=new char[len];//开辟内存空间
        memset(str_,0,len);//初始化
        strcpy(str_,s);//
        std::cout<<"非空串"<<std::endl;
    }
     std::cout<<"myString() 构建"<<k<<"次"<<std::endl;
     k++;
}
myString::myString(const myString & another)//deep 拷贝
{
    int len=strlen(another.str_)+1;
    str_=new char[len];//申请空间
    memset(str_,0,len);//初始化空间
    strcpy(str_,another.str_);
    std::cout<<"myString(const myString & another) deep拷贝"<<cpys<<"次"<<std::endl;
    cpys++;
}
 myString& myString::operator=(const myString & another)//赋值 拷贝
 {
     if(this==&another)
        return *this;
         delete []this->str_;//自己存了  其它对象的地址 为了避免内存泄露
                             //把自己的内存释放掉
     int len=strlen(another.str_)+1;
     str_=new char[len];//申请空间
     memset(str_,0,len);//初始化空间
     strcpy(str_,another.str_);
     return *this;//对象 d1=d2=d3
 }
void myString::dis()
{
    std::cout<<str_<<std::endl;
 
}
myString::~myString()
{
    std::cout<<"~myString() 析构"<<kk<<"次"<<std::endl;
    kk++;
    delete []str_;
}
#include "myString.h"
using namespace std;
// k;//构造次数
// kk;//析构次数
//cpys;//deep 拷贝次数
 
int main()
{
 
        // myString sc;//myString() k=1 ~myString() kk=1
       // sc.dis();
    myString sc1("canadajksadsdsjfsssssssssssssssssssssssssssssssss");
   // myString sc2(sc1);//用已有对象初始化新对象
   // sc1.dis();
    myString sc3;
    sc3=sc1;
    sc3.dis();
    // cout << "Hello World!" << endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值