Constexpr Class in C++
Level 5599 keystrokes
Point has a constexpr constructor and constexpr member functions, so Point objects can be created, added and measured at compile time. p2 = (4, 5) and the squared distance of (3, 4) is 25.
C++ code
1class Point {2 double x_, y_;3public: // constexpr constructor: objects can be built at compile time (defaults 0, 0)4 constexpr Point(double x = 0, double y = 0) : x_(x), y_(y) {} // constexpr getters for the coordinates5 constexpr double x() const { return x_; }6 constexpr double y() const { return y_; } // x² + y², computable at compile time7 constexpr double distanceSquared() const { return x_ * x_ + y_ * y_; } // constexpr addition returns a new Point8 constexpr Point operator+(const Point& other) const {9 return Point(x_ + other.x_, y_ + other.y_);10 }11};12 // constexpr variables are computed by the compiler13constexpr Point origin(0, 0);14constexpr Point p1(3, 4);// (3, 4) + (1, 1) = (4, 5), at compile time15constexpr Point p2 = p1 + Point(1, 1);// 3² + 4² = 2516constexpr auto dist = p1.distanceSquared();17 // Prints "p2: (4, 5)"18cout << "p2: (" << p2.x() << ", " << p2.y() << ")" << endl;// Prints "dist squared: 25"19cout << "dist squared: " << dist << endl;Output
p2: (4, 5) dist squared: 25
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this C++ code and how often they appear.
<× 18(× 15)× 15_× 14;× 12,× 8"× 8{× 6}× 6.× 5