温馨提示×

C++ Point的运算符重载技巧

c++
小樊
91
2024-07-14 10:30:28
栏目: 编程语言

在C++中,可以通过重载运算符来定义自定义类的行为。对于Point类,我们可以重载一些常用的运算符,例如加法、减法、乘法和除法等。

以下是Point类的一些常用运算符重载技巧:

  1. 加法运算符重载:
Point operator+(const Point& p) {
    Point result;
    result.x = this->x + p.x;
    result.y = this->y + p.y;
    return result;
}
  1. 减法运算符重载:
Point operator-(const Point& p) {
    Point result;
    result.x = this->x - p.x;
    result.y = this->y - p.y;
    return result;
}
  1. 乘法运算符重载(点乘):
int operator*(const Point& p) {
    return this->x * p.x + this->y * p.y;
}
  1. 除法运算符重载:
Point operator/(int divisor) {
    Point result;
    result.x = this->x / divisor;
    result.y = this->y / divisor;
    return result;
}

通过重载这些运算符,我们可以方便地对Point对象进行算术运算,使其具有更灵活的使用方式。

0