我理解 constexpr
可以让你在编译时将对象用作常量,但是这种情况的实际应用有哪些呢?我想更好地理解这个关键词,但我找不到一个很好的例子来说明为什么需要在构造函数上使用它。
下面的两个示例都能正常工作,那么为什么要在构造函数上放置 constexpr 呢?
将 constexpr 放在构造函数中的示例:
#include <iostream>
using namespace std;
class Rect
{
public:
constexpr Rect(int width, int height)
: mWidth(width), mHeight(height) {}
constexpr int getArea() const { return mWidth * mHeight; }
private:
int mWidth, mHeight;
};
int main(int argc, char* argv[])
{
constexpr Rect r(8, 2);
cout << r.getArea() << endl; //16
int myArray[r.getArea()]; // OK
return 0;
}
没有在构造函数上使用constexpr:
#include <iostream>
using namespace std;
class Rect
{
public:
Rect(int width, int height)
: mWidth(width), mHeight(height) {}
constexpr int getArea() const { return mWidth * mHeight; }
private:
int mWidth, mHeight;
};
int main(int argc, char* argv[])
{
Rect r(8, 2);
cout << r.getArea() << endl; //16
int myArray[r.getArea()]; // OK
return 0;
}
getArea()
的两个示例中都使用了constexpr
。 - user5390668constexpr
,那么它只有在其参数(包括隐含的*this
)也是常量表达式时才返回常量表达式。 - M.M