继承和动态内存分配——需要为继承类定义 显式析构函数、复制构造函数和赋值运算符

当派生类使用了new时,必须为派生了定义显式析构函数、复制构造函数和赋值运算符。
(这里假设hasDMA类继承自baseDMA类)
显式析构函数:

baseDMA::~baseDMA() // takes care of baseDMA stuff
{
    delete [] label;
}

hasDMA::~hasDMA()
{
    delete [] style;
}

复制构造函数:

baseDMA::baseDMA(const baseDMA & rs)
{
    label = new char[std::strlen(rs.label) + 1];
    std::strcpy(label, rs.label);
    rating = rs.rating;
}

hasDMA::hasDMA(const hasDMA & hs)
            : baseDMA(hs)
{
    style = new char[std::strlen(hs.style) + 1];
    std::strcpy(style, hs.style);
}

赋值运算符:

baseDMA & baseDMA::operator=(const baseDMA & rs)
{
    if (this == &rs)
        return *this;
    delete [] label;
    label = new char[std::strlen(rs.label) + 1];
    std::strcpy(label, rs.label);
    rating = rs.rating;
    return *this;
}

hasDMA & hasDMA::operator=(const hasDMA & hs)
{
    if (this == &hs)
        return *this;
    baseDMA::operator=(hs); // copy base portion
    delete [] style;        // prepare for new style
    style = new char[std::strlen(hs.style) + 1];
    stdLLstrcpy(style, hs.style);
    return *this;
}
原文地址:https://www.cnblogs.com/moonlightpoet/p/5664631.html