首页 > 解决方案 > 构造函数声明为 constexpr

问题描述

我尝试了 IBM 知识中心的示例:我在 Visual Studio 2019 中运行它,它看起来不同:尽管有构造函数,但constexpr我可以根据构造函数输入参数初始化成员D3。以及在构造函数主体中,我可以为D3. 这种差异的原因是什么?哪个构造函数定义为 constexpr ?

struct BASE {
};
struct B2 {
  int i;
};

struct D1 : public BASE {
  //OK, the implicit default constructor of BASE is a constexpr constructor.
  constexpr D1() : BASE(), mem(55) { }
  
  //OK, the implicit copy constructor of BASE is a constexpr constructor.
  constexpr D1(const D1& d) : BASE(d), mem(55) { } 

  //OK, all reference types are literal types.
  constexpr D1(NL &n) : BASE(), mem(55) { }

  //The conversion operator is not constexpr.
  operator int() const { return 55; }      

private:    
  int mem;
};  

struct D3 : B2 {
  //error, D3 must not be a function try block.   
  constexpr D3(int) try : B2(), mem(55) { } catch(int) { }

  //error, illegal statement is in body.
  constexpr D3(char) : B2(), mem(55) { mem = 55; } 
  
  //error, initializer for mem is not a constant expression. 
  constexpr D3(double i) : B2(), mem(i) { }

  //error, implicit conversion is not constexpr. 
  constexpr D3(const D1 &d) : B2(), mem(d) { }                   

  //error, parameter NL is a non-literal type.
  constexpr D3(NL) : B2(), mem(55) { } 

private: 
  int mem;
};

标签: c++constexpr

解决方案


推荐阅读