C++ 的 constexpr类
等级 5599 次按键
Point 拥有 constexpr 构造函数和 constexpr 成员函数,因此可以在编译期创建、相加和计算 Point 对象。p2 = (4, 5),(3, 4) 的距离平方为 25。
C++ 代码
1class Point {2 double x_, y_;3public: // constexpr 构造函数:可在编译期创建对象(默认值 0, 0)4 constexpr Point(double x = 0, double y = 0) : x_(x), y_(y) {} // 返回坐标的 constexpr 访问函数5 constexpr double x() const { return x_; }6 constexpr double y() const { return y_; } // x² + y²,可在编译期计算7 constexpr double distanceSquared() const { return x_ * x_ + y_ * y_; } // constexpr 加法返回新的 Point8 constexpr Point operator+(const Point& other) const {9 return Point(x_ + other.x_, y_ + other.y_);10 }11};12 // constexpr 变量由编译器计算13constexpr Point origin(0, 0);14constexpr Point p1(3, 4);// 在编译期计算 (3, 4) + (1, 1) = (4, 5)15constexpr Point p2 = p1 + Point(1, 1);// 3² + 4² = 2516constexpr auto dist = p1.distanceSquared();17 // 输出“p2: (4, 5)”18cout << "p2: (" << p2.x() << ", " << p2.y() << ")" << endl;// 输出“dist squared: 25”19cout << "dist squared: " << dist << endl;运行结果
p2: (4, 5) dist squared: 25
可以用这段代码练习打字。成绩不会计入排行榜。
这段代码中的符号
这段 C++ 代码中需要输入的符号及其出现次数。
<× 18(× 15)× 15_× 14;× 12,× 8"× 8{× 6}× 6.× 5