In C++, the operator
keyword is used to provide different behaviors for operators.
Basic Concepts#
- Overloading operators allows for custom behavior.
- Overloading operators does not change the inherent precedence and associativity of the operators.
operator
Syntax#
type operator symbol(params)
Here, type
is the return type, and operator symbol
represents the operator to be overloaded. For example, the overload forms of the addition operator and the addition assignment operator are:
// Addition
operator+
// Addition assignment
operator+=
A Simple Example#
The following example demonstrates how to overload the addition operator:
class MyClass {
public:
MyClass(int val) : value(val) {}
// Overload the addition operator
MyClass operator+(const MyClass& other) const {
return MyClass(value + other.value - 1);
}
int getValue() const {
return value;
}
private:
int value;
};
Unoverloadable Operators#
Most operators in C++ can be overloaded, but due to the implementation of the compiler, the following operators cannot be overloaded:
.
.*
::
?:
- Some non-symbol operators
- sizeof
- typeid
- const_cast
- dynamic_cast
- static_cast
Member Function Overloading and Global Function Overloading#
- Member function overloading: Implemented through member functions of a class, where the first parameter is the implicit
this
pointer.
class MyClass {
public:
MyClass(int val) : data(val) {}
// Member function overloading for the addition operator
MyClass operator+(const MyClass& other) const {
return MyClass(data + other.data);
}
private:
int data;
};
- Global function overloading: Implemented through friend functions or ordinary functions, suitable for cases where operations need to be performed on two objects of different types.
class MyClass {
public:
MyClass(int val) : data(val) {}
// Declare friend function to access private members
friend MyClass operator+(const MyClass& lhs, const MyClass& rhs);
private:
int data;
};
// Global function overloading for the addition operator
MyClass operator+(const MyClass& lhs, const MyClass& rhs) {
return MyClass(lhs.data + rhs.data);
}