C ++ constexpr编译问题

时间:2018-07-13 03:57:44

标签: c++ compiler-errors constexpr

我无法为基本的矢量图形点类编译此测试用例。请帮助我找出丢失的内容。谢谢!

编译错误:必须使用常量表达式初始化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;
    }
}

2 个答案:

答案 0 :(得分:2)

您还需要使构造函数为constexpr

有关constexpr(包括构造函数)的行为的更多信息,请参见this page

答案 1 :(得分:1)

有两个单独的错误。

  1. 您需要使构造函数Ctrl+Shift+P
  2. 您需要将函数移到头文件(使用时constexpr函数的主体必须可见)。

Live demo