C++系列十:日常学习-操作符重载

发布时间 2023-09-06 09:43:09作者: cactus9

介绍:

在 C++ 中,操作符重载(Operator Overloading)是一种允许我们自定义或改变某些操作符的行为的技术。

案例:

单个参数的简单例子:
#include <iostream>  
  
class MyNumber {  
private:  
    double value;  
  
public:  
    MyNumber(double v) : value(v) {}  
  
    // Overload + operator  
    MyNumber operator+(const MyNumber& other) const {  
        return MyNumber(value + other.value);  
    }  
  
    // Overload - operator  
    MyNumber operator-(const MyNumber& other) const {  
        return MyNumber(value - other.value);  
    }  
  
    // Overload * operator  
    MyNumber operator*(const MyNumber& other) const {  
        return MyNumber(value * other.value);  
    }  
  
    // Overload / operator  
    MyNumber operator/(const MyNumber& other) const {  
        if(other.value != 0.0) {  
            return MyNumber(value / other.value);  
        } else {  
            std::cout << "Error: Division by zero." << std::endl;  
            return MyNumber(0.0);  
        }  
    }  

    // Overload += operator  
    MyNumber& operator+=(const MyNumber& other) {  
        value += other.value;  
        return *this;  
  
    void printValue() const {  
        std::cout << value << std::endl;  
    }  
};  
  
int main() {  
    MyNumber a(11.0);  
    MyNumber b(2.0);  
    MyNumber c = a + b;  
    c.printValue();  // Output: 13.0  
    MyNumber d = a - b;  
    d.printValue();  // Output: 9.0  
    MyNumber e = a * b;  
    e.printValue();  // Output: 22.0  
    MyNumber f = a / b;  
    f.printValue();  // Output: 5.5  

    a += b;          // a = a + b;  
    c.printValue();  // Output: 23.0  
    return 0;  
}