答案:静态数组在类中声明时固定大小,内存随对象创建自动分配;动态数组通过指针声明,需手动管理内存分配与释放,防止内存泄漏。
在c++中,类的成员可以是数组,这类数组成员分为静态数组(固定大小)和动态数组(运行时分配)。合理管理这两类数组成员对程序的稳定性与资源利用至关重要。
静态数组成员
静态数组成员是指在类定义时大小已知、内存随对象创建自动分配的数组。
声明方式简单,直接指定数组大小:
class MyArrayClass { private: int data[10]; // 静态数组,固定大小为10 public: void setValue(int index, int value) { if (index >= 0 && index < 10) { data[index] = value; } } int getValue(int index) const { return (index >= 0 && index < 10) ? data[index] : 0; } };
优点是无需手动管理内存,构造函数中可直接初始化。注意边界检查以避免越界访问。
立即学习“C++免费学习笔记(深入)”;
动态数组成员
动态数组成员在运行时根据需要分配内存,适用于大小不固定的场景。
使用指针配合 new/delete 或 new[]/delete[] 进行动态管理:
class DynamicArray { private: int* data; int size; <p>public: // 构造函数:动态分配数组 DynamicArray(int s) : size(s) { data = new int[size](); // 初始化为0 }</p><pre class='brush:php;toolbar:false;'>// 析构函数:释放内存 ~DynamicArray() { delete[] data; } // 拷贝构造函数 DynamicArray(const DynamicArray& other) : size(other.size) { data = new int[size]; for (int i = 0; i < size; ++i) { data[i] = other.data[i]; } } // 赋值操作符 DynamicArray& operator=(const DynamicArray& other) { if (this != &other) { delete[] data; // 释放原内存 size = other.size; data = new int[size]; for (int i = 0; i < size; ++i) { data[i] = other.data[i]; } } return *this; } int& operator[](int index) { return data[index]; } const int& operator[](int index) const { return data[index]; } int getSize() const { return size; }
};
关键点:
- 必须实现析构函数来释放内存
- 遵循“三法则”:若需要析构函数,通常也需要自定义拷贝构造和赋值操作符
- 避免浅拷贝导致的双重释放问题
现代C++推荐方式:使用std::vector
手动管理动态数组容易出错。推荐使用 std::vector 替代原始动态数组:
class SafeArray { private: std::vector<int> data; <p>public: SafeArray(int size) : data(size, 0) {}</p><pre class='brush:php;toolbar:false;'>int& operator[](int index) { return data.at(index); // 带边界检查 } const int& operator[](int index) const { return data.at(index); } void resize(int newSize) { data.resize(newSize); } size_t size() const { return data.size(); }
};
std::vector 自动管理内存,支持拷贝、赋值,无需手动实现析构函数或三法则,更安全高效。
基本上就这些。静态数组适合固定小数据,动态数组需谨慎管理资源,而 std::vector 是现代C++中最推荐的选择。不复杂但容易忽略细节,尤其是内存释放和拷贝语义。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END