c++面向对象程序设计 笔记三

class with pointer member

1.三个特殊的函数

拷贝构造,拷贝赋值,析构

2.ctor 和 dtor

inline String::String(const char* cstr = 0)
{
    if(cstr)
    {
        m_data = new char[strlen(cstr)+1];
        strcpy(m_data, cstr);
    }
    else
    {
        m_data = new char[1];
        *m_data = '\0';
    }
}

inline String::~String()
{
    delete[] m_data;
}

{
    String s1();
    String s2("hello");

    String* p = new String("hello");
    delete p;
}

3.带有指针的类必须有拷贝构造和拷贝赋值(自订)

深拷贝和浅拷贝

inline String& String::operator=(const String& str)
{
    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;
}
发布了44 篇原创文章 · 获赞 5 · 访问量 1395

猜你喜欢

转载自blog.csdn.net/qq_33776188/article/details/104643523
今日推荐