A binary operator can be defined by either a non-static member function taking
时间: 2024-05-01 14:23:35 浏览: 91
one argument or a non-member function taking two arguments. In the case of a non-static member function, the left operand is the object on which the function is called, and the right operand is passed as an argument. For example, consider the following class definition:
```
class Complex {
private:
double real;
double imag;
public:
Complex(double r, double i) : real(r), imag(i) {}
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
};
```
In this example, the `+` operator is defined as a non-static member function that takes one argument of type `Complex`. When this operator is used, the left operand is the object on which the function is called, and the right operand is passed as the argument.
On the other hand, a binary operator can also be defined as a non-member function taking two arguments. In this case, neither of the arguments is implicitly the object on which the function is called, so both must be explicitly passed as arguments. For example:
```
Complex operator+(const Complex& a, const Complex& b) {
return Complex(a.real + b.real, a.imag + b.imag);
}
```
This definition allows the `+` operator to be used with two `Complex` objects, rather than just one.
阅读全文