一元运算符是指只对一个操作数进行操作的运算符。在编程中,我们可以通过重载这些运算符来实现自定义的行为。以下是一些常见的一元运算符及其重载方法:
递增(++)和递减(--)运算符
```cpp
class Distance {
public:
int feet;
int inches;
Distance() { feet = 0; inches = 0; }
Distance(int f, int i) { feet = f; inches = i; }
Distance& operator++() { // 前置递增
++feet;
return *this;
}
Distance operator++(int) { // 后置递增
Distance temp = *this;
++feet;
return temp;
}
Distance& operator--() { // 前置递减
--feet;
return *this;
}
Distance operator--(int) { // 后置递减
Distance temp = *this;
--feet;
return temp;
}
};
```
一元减(-)运算符
```cpp
Distance operator-(const Distance& other) {
return Distance(-other.feet, -other.inches);
}
```
逻辑非(!)运算符
```cpp
bool operator!(const Distance& d) {
return d.feet == 0 && d.inches == 0;
}
```
取地址(&)运算符
```cpp
Distance& operator&() {
// 这里可以添加自定义行为,例如返回当前对象的引用
return *this;
}
```
解引用(*)运算符
```cpp
Distance operator*(int scalar) const {
return Distance(feet * scalar, inches * scalar);
}
Distance operator/(int scalar) const {
return Distance(feet / scalar, inches / scalar);
}
```
取模(%)运算符
```cpp
Distance operator%(int scalar) const {
return Distance(feet % scalar, inches % scalar);
}
```
一元加(+)运算符
```cpp
Distance operator+(const Distance& other) const {
return Distance(feet + other.feet, inches + other.inches);
}
```
一元减(-)运算符(用于指针或引用)
```cpp
Distance operator-(const Distance& other) const {
return Distance(feet - other.feet, inches - other.inches);
}
```
一元加(+)运算符(用于指针或引用)
```cpp
Distance& operator+=(const Distance& other) {
feet += other.feet;
inches += other.inches;
return *this;
}
```
一元减(-)运算符(用于指针或引用)
```cpp
Distance& operator-=(const Distance& other) {
feet -= other.feet;
inches -= other.inches;
return *this;
}
```
通过重载这些一元运算符,我们可以为自定义类型(如 `Distance` 类)提供丰富的操作符支持,从而使代码更加直观和易于使用。