`operator` — C++ Keyword
`operator` — C++ Keyword
The operator keyword in C++: defines overloaded operators for user-defined types.
`operator` — C++ Keyword
The operator keyword in C++: defines overloaded operators for user-defined types.
Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.
operatorUsed to define overloaded operator functions for user-defined types, allowing objects to be used with standard C++ operators (+, ==, [], etc.).
// Member operator
return-type operator symbol(params);
// Non-member (free) operator
return-type operator symbol(left-param, right-param);
// Conversion operator
explicit operator TargetType() const;
#include <print>
struct Vec2 {
double x, y;
Vec2 operator+(const Vec2& o) const {
return {x + o.x, y + o.y};
}
Vec2& operator+=(const Vec2& o) {
x += o.x; y += o.y; return *this;
}
bool operator==(const Vec2& o) const = default; // C++20 defaulted
// Subscript
double& operator[](int i) { return i == 0 ? x : y; }
// Conversion to bool
explicit operator bool() const { return x != 0 || y != 0; }
};
// Free-function shift-out for printing
std::ostream& operator<<(std::ostream& os, const Vec2& v) {
return os << '(' << v.x << ',' << v.y << ')';
}
int main() {
Vec2 a{1, 2}, b{3, 4};
Vec2 c = a + b;
std::println("{:.0f} {:.0f}", c.x, c.y); // 4 6
std::println("{}", (a == b)); // false
std::println("{}", static_cast<bool>(a)); // true
}
= default (C++20) to generate == and <=> (spaceship) automatically.int main() {
// Pick one facility from this reference page.
// Write the smallest program that exercises its main precondition,
// complexity rule, or lifetime constraint before scaling up.
return 0;
}