关于constexpr

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于constexpr相关的知识,希望对你有一定的参考价值。

1.以下语句是错误的:

int i=5;
constexpr int ic=i;

 constexpr期望得到一个常量的表达式,因此其初始化器必须是常量而不能是变量

 

2.用constexpr定义的指针是顶层而非底层的,即:它指向的地址是固定不变的。值得注意到是,在函数体内,变量的地址是可以改变的(即便它是常量)。只有函数体外的变量地址是不变的(即便它不是常量)。因此,以下语句是合法的:

int test(int n)
{
    n*=2;
    return n;
}

int t=5;
int a=test(t);

int main()
{
    constexpr int *p=&a;
    cout<<*p<<endl;
    return 0;
}

以上代码输出结果为10

以上是关于关于constexpr的主要内容,如果未能解决你的问题,请参考以下文章