C++constexpr编译问题

C++ constexpr compilation issue

本文关键字:问题 编译 C++constexpr      更新时间:2023-10-16

我无法为基本矢量图形点类编译此测试用例。请帮我弄清楚缺了什么。谢谢

编译错误:Constexpr变量"i"必须由常量表达式初始化

测试用例:

TEST(constexprPoint, Point)
{
constexpr int i = VG::Point{4, 5}.getX(); // <-- compile error
CHECK_EQUAL(i, 4);
}

头文件:

namespace VG {
class Point{
public:
Point(const int x, const int y) : myX{x},myY{y} {}
constexpr int getX() const;
constexpr int getY() const;
private:
const int myX, myY;
};
}

源文件:

namespace VG {
constexpr int Point::getX() const {
return myX;
}
constexpr int Point::getY() const {
return myY;
}
}

您还需要使构造函数成为constexpr

有关constexpr(包括构造函数(行为的更多信息,请参阅本页。

有两个单独的错误。

  1. 您需要使构造函数constexpr
  2. 您需要将函数移到头文件中(constexpr函数的主体在使用时必须可见(

实时演示