为了实现赋值运算符重载,需要注意以下几点:

  1. 确保在赋值运算符重载函数中,要自我赋值检测。
  2. 释放当前对象的资源。
  3. 深拷贝源对象的资源到当前对象。

下面是基于你提供的设定,使用GPT-3.5 Turbo版本回答你的问题,实现赋值运算符重载=的代码:

//缓冲区
class DataBuffer
{
private:
    char *pBuf;     //指向一块空间
    int max_len;    //pBuf指向的空间的大小
public:
    //普通的 构造函数 
    DataBuffer(int maxl = 0) : max_len(maxl)
    {
        cout << "普通的 构造函数 DataBuffer(int maxl = 0)" << endl;
        if (max_len > 0)
        {
            pBuf = (char *)malloc(max_len);
        }
    }

    //自己设计一个'拷贝构造函数',实现 深拷贝
    DataBuffer(const DataBuffer &d) : max_len(d.max_len), pBuf(nullptr)
    {
        //深拷贝--> 重新分配空间 并 拷贝
        cout << "拷贝构造函数 DataBuffer(const DataBuffer &d)" << endl;

        if (max_len > 0)
        {
            pBuf = (char *)malloc(max_len);

            MemCopy(d.pBuf, max_len);
        }
    }

    //析构函数 
    ~DataBuffer()
    {
        if (pBuf)
        {
            free(pBuf);
            cout << "析构函数 ~DataBuffer()" << endl;
        }
    }

    void MemCopy(const char *p, int n)
    {
        if (pBuf && n <= max_len)
        {
            memcpy(pBuf, p, n);
        }
    }

    void print(void) const
    {
        cout << pBuf << endl;
    }

    // = 赋值运算符重载 
    DataBuffer &operator=(const DataBuffer &d)
    {
        if (this == &d) // 自我赋值检测
            return *this;

        if (pBuf)
        {
            free(pBuf); // 释放当前对象的资源
        }

        max_len = d.max_len; // 深拷贝源对象的资源到当前对象
        if (max_len > 0)
        {
            pBuf = (char *)malloc(max_len);
            MemCopy(d.pBuf, max_len);
        }

        return *this;
    }
};

现在我们可以使用赋值运算符重载来将一个DataBuffer对象赋值给另一个对象,例如:

int main()
{
    DataBuffer buffer1(100);
    strcpy(buffer1.pBuf, "Hello, world!");
    buffer1.print(); // 输出:Hello, world!
    
    DataBuffer buffer2;
    buffer2 = buffer1; // 使用赋值运算符重载
    buffer2.print();  // 输出:Hello, world!
    
    return 0;
}

这样,我们就实现了赋值运算符重载,将一个DataBuffer对象的内容赋值给了另一个对象。

C++ 赋值运算符重载:DataBuffer 类示例

原文地址: http://www.cveoy.top/t/topic/bSjP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录