c++ constexpr 关键字

先看一个简单的例子:

	class test{
 public:
  constexpr test(){

  }

  constexpr int operator + (const test& rhs){
    return 1;
  }
};

int main() {
  test t;                                 
  constexpr int b = t + test();     // 可以编译通过


  int w = 10;                     // 
  constexpr int c = w + 2;        // 编译不通过, w不是constexpr
  return 0;
}

如果改成:

class test{
 public:
  constexpr test(){
      a= 12;
  }

  constexpr int operator + (const test& rhs){
    return 1 + a;
  }
  int a;
};

int main() {
  test t;                      
  constexpr int b = t + test();     //编译不通过, b不是constexpr


  int w = 10;                   
  constexpr int c = w + 2;        // 编译不通过, c不是constexpr
  return 0;
}

这里的test 构造函数声明成 constexpr 但是 t的变量并不是constexpr , 主要是
+ test() 能够变成 constexpr.
constexpr int b = t + test();
展开就是
constexpr int b = t.operator+( test() );

  • 要点:
    1.constexpr constructors ,构造函数可以声明静态初始化
#include <iostream>

struct test {
    int val; 
    constexpr test(int val) : val(val) { }
    
};

template<int N>
struct CC {
    double m[N]; 
};

int main()
{   
    constexpr int c =12;
    constexpr auto w  = test(c);
   // w.val =  12  // 编译报错, w 是read -only, 不可以被修改
    CC<w.val> k; // usage where compile time constant is required
    std::cout << std::end(k.m) - std::begin(k.m) << std::endl; 
    return 0;
}

demo

但是constexpr constructors 也不是这个类所有的实例都不可以被修改,类内的对象还是可以修改的。

#include <iostream>

struct test {
    int val;
    constexpr test(int val) : val(val) { }
};

int main()
{
    test a(1); 
    ++a.val; 
    std::cout << a.val << std::endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝鲸123

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值