C++
Beginner
1 min read
Operator Overloading
Example
#include <iostream>
#include <cmath> // std::sqrt
struct Vector2D {
double x, y;
// Constructor
Vector2D(double x = 0, double y = 0) : x(x), y(y) {}
// Member: unary negation
Vector2D operator-() const { return {-x, -y}; }
// Member: compound assignment
Vector2D& operator+=(const Vector2D& rhs) {
x += rhs.x; y += rhs.y; return *this;
}
double length() const { return std::sqrt(x*x + y*y); }
};
// Free: binary addition (symmetrical)
Vector2D operator+(Vector2D lhs, const Vector2D& rhs) {
lhs += rhs; // reuse compound assignment
return lhs;
}
// Free: equality
bool operator==(const Vector2D& a, const Vector2D& b) {
return a.x == b.x && a.y == b.y;
}
// Free: stream insertion (friend not needed if using public members)
std::ostream& operator<<(std::ostream& os, const Vector2D& v) {
return os << "(" << v.x << ", " << v.y << ")";
}
int main() {
Vector2D a{3.0, 0.0}, b{0.0, 4.0};
Vector2D c = a + b;
std::cout << "a + b = " << c << "\n"; // (3, 4)
std::cout << "length = " << c.length() << "\n"; // 5
std::cout << std::boolalpha << (a == b) << "\n"; // false
return 0;
}