加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

具有聚合初始化的C 11构造函数委派

发布时间:2020-12-14 05:01:48 所属栏目:百科 来源:网络整理
导读:是否可以在我自己的默认ctor定义中调用聚合初始化? GCC使用以下代码抱怨“错误:构造函数委托给自己”: struct X { int x,y,z,p,q,r; X(): x{},y{},z{},p{},q{},r{} { } // cumbersome//X(): X{} { } // the idea is nice but doesn't compile}; 我现在在c
是否可以在我自己的默认ctor定义中调用聚合初始化?

GCC使用以下代码抱怨“错误:构造函数委托给自己”:

struct X {
  int x,y,z,p,q,r;
  X(): x{},y{},z{},p{},q{},r{} { }  // cumbersome
//X(): X{} { }  // the idea is nice but doesn't compile
};

我现在在ctor体中使用memset(this,sizeof(* this)).

解决方法

一种方法是以下列方式欺骗重载决策:

struct X {
  int x,r;
  X(int) : x{},r{} { }
  X() : X(0) { }
};

另一种方法是使用类内默认成员初始化:

struct X {
  int x = 0,y = 0,z = 0,p = 0,q = 0,r = 0;
};

在您的具体示例中,您还可以:

struct X {
  std::array<int,6> vars{};
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读