C++ 新特性

2023-11-07  本文已影响0人  hjm1fb
#include <iostream>
using namespace std;
class Foo
{
public:
    constexpr explicit Foo(int i) : _i(i) {}
    
        constexpr int getValue() const
    {
        return _i;
    }

    constexpr int valuePlusOne() const
    {
        const_cast<Foo *>(this)->_i = _i + 1;
        return _i;
    }
    
private:
    int _i;
};

int main()
{
    printf("__cplusplus is %d \n", __cplusplus);
    constexpr Foo foo(1);// 编译时:
    printf("foo is %d", foo.getValue()); //运行时 第一行打印为1
    foo.valuePlusOne();//Run Time 
    printf("foo is %d", foo.getValue());//运行时 第二行打印为2
    constexpr int v = foo.getValue();// 编译时 说明constexpr修饰的函数只有赋值给constexpr变量(构造函数除外),才能确保为编译时运行
    printf("v is %d", v);// 编译时 第三行输出为1
    static_assert(foo.getValue() == 1, "a");// 无报错
}
上一篇 下一篇

猜你喜欢

热点阅读