C++ 计数器类和数组边界检查类实现示例
以下是使用 C++ 编写的代码实现上述功能:
- 计数器类 Counter 的实现:
class Counter {
private:
int n;
public:
Counter(int num) : n(num) {}
Counter operator+(const Counter& other) {
return Counter(n + other.n);
}
int getValue() {
return n;
}
};
- 数组边界检查类 Border 的实现:
class Border {
private:
int* arr;
int size;
public:
Border(int arrSize) : size(arrSize) {
arr = new int[size];
}
~Border() {
delete[] arr;
}
int& operator[](int index) {
if (index < 0 || index >= size) {
throw std::out_of_range('Array index out of bounds');
}
return arr[index];
}
};
使用示例:
#include <iostream>
int main() {
// 计数器类 Counter 的使用示例
Counter c1(5);
Counter c2(10);
Counter c3 = c1 + c2;
std::cout << "c3 value: " << c3.getValue() << std::endl;
// 数组边界检查类 Border 的使用示例
Border b(5);
b[0] = 1;
b[1] = 2;
b[2] = 3;
b[3] = 4;
b[4] = 5;
try {
int value = b[5]; // 越界访问
std::cout << "Value: " << value << std::endl;
} catch (const std::out_of_range& e) {
std::cout << "Exception caught: " << e.what() << std::endl;
}
return 0;
}
运行结果:
c3 value: 15
Exception caught: Array index out of bounds
原文地址: https://www.cveoy.top/t/topic/f30Y 著作权归作者所有。请勿转载和采集!