zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    汉罗塔
    汉罗塔动画实现
    画五星红旗
    科学与可视化
    类和正则表达式
    圆周率
    汉诺塔
    jieba库
    Python图片处理
    随手笔记
  • 原文地址:https://www.cnblogs.com/larry-xia/p/10265473.html
Copyright © 2011-2022 走看看