我试图从Stroustrup的书“使用C ++的原理和实践”第二版中编译constexpr函数的示例(在VS15上)。我得到标题中提到的错误。除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}
}
您的类Point
无法通过constexpr scale返回,因为它没有任何constexpr
构造函数。
所以应该是:
struct Point {
public:
double x;
double y;
constexpr Point(double x, double y) : x(x), y(y){}
};