定义一个计数器类counter,包含私有成员int n ,重载运算符“+”
时间: 2024-05-24 20:12:07 浏览: 89
class Counter {
private:
int n;
public:
Counter() : n(0) {}
Counter(int n) : n(n) {}
int get() const { return n; }
void set(int n) { this->n = n; }
Counter operator+(const Counter& other) const {
return Counter(n + other.n);
}
Counter operator-(const Counter& other) const {
return Counter(n - other.n);
}
Counter operator*(const Counter& other) const {
return Counter(n * other.n);
}
Counter operator/(const Counter& other) const {
if (other.n == 0) {
throw std::invalid_argument("Division by zero");
}
return Counter(n / other.n);
}
bool operator==(const Counter& other) const {
return n == other.n;
}
bool operator!=(const Counter& other) const {
return !(*this == other);
}
bool operator<(const Counter& other) const {
return n < other.n;
}
bool operator>(const Counter& other) const {
return n > other.n;
}
bool operator<=(const Counter& other) const {
return n <= other.n;
}
bool operator>=(const Counter& other) const {
return n >= other.n;
}
};
阅读全文