使用 C++ 实现计数器类和数组越界检查类

本文将使用 C++ 编写两个类:

  1. 计数器类 (Counter):定义一个计数器类,包含私有成员 int n,并重载 + 运算符实现对象相加。
  2. 数组越界检查类 (Border):设计一个类,通过重载 [] 运算符检查数组是否越界。

以下是实现代码:

#include <iostream>

class Counter {
private:
    int n;

public:
    Counter(int num) : n(num) {}

    Counter operator+(const Counter& other) const {
        return Counter(n + other.n);
    }

    int getValue() const {
        return n;
    }
};

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) {
            std::cout << '数组越界!' << std::endl;
            exit(1);
        }
        return arr[index];
    }
};

int main() {
    // 测试 Counter 类的重载运算符 '+'
    Counter c1(5);
    Counter c2(10);
    Counter c3 = c1 + c2;
    std::cout << 'c3 的值为:' << c3.getValue() << std::endl;

    // 测试 Border 类的重载运算符 '[]'
    Border b(3);
    b[0] = 1;
    b[1] = 2;
    b[2] = 3;
    std::cout << 'b[1] 的值为:' << b[1] << std::endl;
    std::cout << 'b[3] 的值为:' << b[3] << std::endl; // 数组越界

    return 0;
}

运行结果:

c3 的值为:15
b[1] 的值为:2
数组越界!

代码解析:

  • Counter 类
    • 私有成员 n 用于存储计数器的值。
    • 构造函数 Counter(int num) 初始化 n
    • 重载 + 运算符,实现两个 Counter 对象相加。
    • 成员函数 getValue() 返回 n 的值。
  • Border 类
    • 私有成员 arr 指向动态分配的数组,size 记录数组大小。
    • 构造函数 Border(int arrSize) 初始化 arrsize
    • 析构函数 ~Border() 释放动态分配的内存。
    • 重载 [] 运算符,检查索引是否越界,如果越界则输出错误信息并终止程序,否则返回对应数组元素的引用。

总结:

本文通过代码示例展示了如何使用 C++ 实现计数器类和数组越界检查类,并解释了代码实现的细节。希望对读者理解 C++ 类的设计和使用有所帮助。

C++ 代码实现计数器类和数组越界检查类

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

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