c++

如何在C++中实现运算符重载

小樊
83
2024-08-18 07:43:38
栏目: 编程语言

在C++中,可以通过定义成员函数或非成员函数来实现运算符重载。以下是一些示例代码:

  1. 重载加法运算符:
class Complex {
private:
    double real;
    double imaginary;
public:
    Complex(double r, double i) : real(r), imaginary(i) {}

    Complex operator+(const Complex& other) {
        return Complex(real + other.real, imaginary + other.imaginary);
    }
};

int main() {
    Complex c1(1, 2);
    Complex c2(3, 4);
    Complex result = c1 + c2;
    return 0;
}
  1. 重载自增运算符:
class Number {
private:
    int value;
public:
    Number(int v) : value(v) {}

    Number& operator++() {
        value++;
        return *this;
    }
};

int main() {
    Number num(5);
    ++num;
    return 0;
}
  1. 重载流插入运算符:
#include <iostream>

class Complex {
private:
    double real;
    double imaginary;
public:
    Complex(double r, double i) : real(r), imaginary(i) {}

    friend std::ostream& operator<<(std::ostream& os, const Complex& c) {
        os << c.real << " + " << c.imaginary << "i";
        return os;
    }
};

int main() {
    Complex c(1, 2);
    std::cout << c << std::endl;
    return 0;
}

需要注意的是,运算符重载一般应该符合运算符的原有语义,遵循常规的运算符规则,并不应该引入令人困惑的行为。

0
看了该问题的人还看了