变长数组(C++)

刚刚复习了一下C++中的类,记录一下变长数组的代码
首先,类中包括两个成员变量
m_len:对应数组中的元素个数
m_p:指向数组的首地址

成员方法:
带参构造函数:传入数组中元素个数,并开辟该元素个数的内存空间
拷贝构造函数:用于深拷贝变长数组
析构函数:释放数组占用的内存空间
length():返回数组的长度
display():打印数组元素
常成员函数:int operator[](int i) const,用于读取单个数组变量
int &operator[](int i),用于写入数组变量

#include <iostream>
using namespace std;

class Array{
public:
    Array(int len); // 构造函数,传入数组长度,申请内存空间
    Array(const Array &arr); // 拷贝构造函数,深拷贝,另开辟内存空间
    ~Array(); // 析构函数,释放内存空间

    int operator[](int i) const{ return m_p[i]; } // 重载[],用来读取数组变量
    int &operator[](int i) { return m_p[i]; } // 重载[],用来写入数组变量
    int length() const { return this->m_len; }
    void display();
private:
    int m_len;
    int *m_p;
};

Array::Array(int len): m_len(len) {
    m_p = new int[len];
}

Array::Array(const Array &arr) {
    this->m_len = arr.m_len;
    this->m_p = new int[this->m_len];
    memcpy(this->m_p, arr.m_p, sizeof(int) * this->m_len);
}

Array::~Array() {
    delete[] this->m_p;
    this->m_p = NULL;
}

void Array::display() {
    for (int i=0; i<this->m_len; i++) {
        if (i == this->m_len - 1) {
            cout << *(m_p + i) << endl;
        }
        else {
            cout << *(m_p + i) << " ";
        }
    }
}

int main() {
    Array arr1(5);
    for (int i=0; i<arr1.length(); i++) {
        arr1[i] = i+10;
    }

    cout << "arr1: \n";
    arr1.display();

    Array arr2 = arr1;
    arr2[3] = 100;
    cout << "arr2: \n";
    arr2.display();

    // 不会改变 arr1 
    cout << "arr1: \n";
    arr1.display();
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值