C++三大函数:析构函数、复制构造函数和operator=

在C++中,伴随类的是已经写好的三个特殊函数:析构函数、复制构造函数和operator=。在多数情况下,都可以采用编译器提供的默认操作,有时候确不行。

对于一个类含有数据成员为指针且深复制很重要时,一般的做法是必须实现析构函数、复制构造函数和operator=。

class IntCell
{
public:
    explicit IntCell(int a = 0);

    IntCell(const IntCell& rhs);
    ~IntCell();
    const IntCell& operator=(const IntCell& rhs);

    int read() const;
    void write(int x);
private:
    int* storedValue;
};
//////////////////////////////
IntCell::IntCell(int a)
{
    storedValue = new int(a);
}
IntCell::IntCell(const IntCell& rhs)
{
    storedValue = new int(*rhs.storedValue);
}
IntCell::~IntCell()
{
    delete storedValue;
}
const IntCell& IntCell::operator=(const IntCell& rhs)
{
    if (this != &rhs)
        *storedValue = *rhs.storedValue;
    return *this;
}
int IntCell::read() const
{
    return *storedValue;
}
void IntCell::write(int x)
{
    *storedValue = x;
}

 

posted @ 2019-01-14 10:17  summer91  阅读(692)  评论(0编辑  收藏  举报