- // C++ program to demonstrate uses of constexpr in constructor
- #include <bits/stdc++.h>
- using namespace std;
- // A class with constexpr constructor and function
- class Rectangle
- {
- int _h, _w;
- public:
- // 修饰一个结构体
- constexpr Rectangle (int h, int w) : _h(h), _w(w) {}
- // 修饰一个函数,_h, _w为全局,并且在实例化时就已经是初始化后的常量了
- constexpr int getArea () { return _h * _w; }
- };
- int main()
- {
- // 对象在编译时就已经初始化了
- constexpr Rectangle obj(10, 20);
- cout << obj.getArea();
- return 0;
- }