函数 "scale" 之前未声明为 constexpr

function "scale" was previously not declared constexpr

我尝试编译(在 VS15 上)Stroustrup 的书 "Principles and practice using C++" 第二版中的 constexpr 函数示例。我得到了标题中提到的错误。除了 struct Point.

所有代码都来自本书
struct Point {
public:
    double x;
    double y;
    Point(double x, double y) : x(x), y(y){}
};
constexpr double xscale = 10;   // scalling factors
constexpr double yscale = 0.8;

constexpr Point scale(Point p) { return{ xscale*p.x,yscale*p.y }; };

void user(Point p1)
{
    Point p2{ 10,10 };
    Point p3 = scale(p1);   // OK: p3=={100,8}; run-time evaluation si fine
    Point p4 = scale(p2);   // p4 == {100,8}

    constexpr Point p5 = scale(p1); // error: scale(p1) is not a constant
                                    // expression
    constexpr Point p6 = scale(p2); // p6=={100,8}
}

您的 class Point 无法由 constexpr scale 返回,因为它没有任何 constexpr 构造函数。

所以应该是:

struct Point {
public:
    double x;
    double y;
    constexpr Point(double x, double y) : x(x), y(y){}
};

Demo