创建一个类DoubleSubscriptedArray。在构造阶段该类能够创建一个包含任意行、任意列的数组。类还提供operator函数进行双下标运算
#include
class DoubleSubscriptedArray { public: // 构造函数 DoubleSubscriptedArray(int rows, int cols) : m_rows(rows), m_cols(cols) { if (rows <= 0 || cols <= 0) { throw std::invalid_argument("Invalid array size."); } m_data = new int[rows * cols]; }
// 析构函数
~DoubleSubscriptedArray() {
delete[] m_data;
}
// 双下标运算符
int& operator()(int row, int col) {
if (row < 0 || row >= m_rows || col < 0 || col >= m_cols) {
throw std::out_of_range("Array index out of range.");
}
return m_data[row * m_cols + col];
}
// 获取数组行数
int getRows() const {
return m_rows;
}
// 获取数组列数
int getCols() const {
return m_cols;
}
private: int* m_data; // 存储数据的指针 int m_rows; // 数组行数 int m_cols; // 数组列数 };
int main() { DoubleSubscriptedArray arr(2, 3);
// 赋值
arr(0, 0) = 1;
arr(0, 1) = 2;
arr(0, 2) = 3;
arr(1, 0) = 4;
arr(1, 1) = 5;
arr(1, 2) = 6;
// 输出
for (int i = 0; i < arr.getRows(); i++) {
for (int j = 0; j < arr.getCols(); j++) {
std::cout << arr(i, j) << " ";
}
std::cout << std::endl;
}
// 尝试越界访问
try {
arr(-1, 0);
} catch (std::out_of_range& e) {
std::cout << e.what() << std::endl;
}
// 尝试非法构造数组
try {
DoubleSubscriptedArray arr2(-1, 3);
} catch (std::invalid_argument& e) {
std::cout << e.what() << std::endl;
}
return 0;
原文地址: https://www.cveoy.top/t/topic/fIMF 著作权归作者所有。请勿转载和采集!