3.27

#include <iostream>
#include <iomanip>

class Mystring
{
private:
    char* str;           //记录c风格的字符串
    int size;            //记录字符串的实际长度
    char c;
public:
    Mystring();          
    Mystring(const char* s);
    ~Mystring();

    Mystring(const Mystring& other);
    Mystring& operator=(const Mystring& other);
    int getsize();
    const char* c_str() const;
    char& at(int pos);
    inline bool empty() const;
};

#include "Rect.h"
#include <string.h>

Mystring::Mystring():size(20)
{
	str = new char[size];           
    strcpy(str, "");
    std::cout << "无参"<< std::endl;
}

Mystring::Mystring(const char* s)
{
    size = strlen(s);
    str = new char[size + 1];
    strcpy(str, s);

    std::cout << "有参"<< std::endl;
}

Mystring::~Mystring()
{
    //std::cout << this << std::endl;
    delete []str;
    
}

Mystring::Mystring(const Mystring& other) 
{
    size = other.size;
    c = other.c;
    str = new char[size + 1];
    strcpy(str, other.str); 
    std::cout << "调用了深拷贝构造函数" << std::endl;
}

Mystring& Mystring::operator=(const Mystring& other)
{
    this->size = other.size;
    strcpy(this->str,other.str);
    this->c = other.c;
    std::cout << "调用了深拷贝赋值函数" << std::endl;
    return *this;
}

int Mystring::getsize()
{
    return size;
}

char& Mystring::at(int pos)
{
    std::string s = str;
    if (pos < 0 || pos >= s.size())
    {
        std::cout << "越界访问" << std::endl;
    }
    c = s.at(pos);
    return c;
}

inline bool Mystring::empty() const
{
    std::string s = str;
    return s.empty();
}

const char* Mystring::c_str() const 
{
    return str;
}




#include <iostream>
#include <string>
#include "Rect.h"


int main()
{
	Mystring s1("hello word!");
	Mystring s2(s1);

	std::cout << s1.c_str() << std::endl;
	std::cout << s2.c_str() << std::endl;

	Mystring s3;
	s3 = s1;     
	std::cout << s3.c_str() << std::endl;
	return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值