如何保留隐式声明的聚合初始化构造函数? [英] How to keep the implicitly declared aggregate initialization constructor?
问题描述
假设我有一个这样的类:
struct X {
char buf [10];
};
X x { abc};
此编译。但是,如果我将用户定义的构造函数添加到该类,则将删除此隐式声明的聚合初始化构造函数:
struct X {
char buf [10];
X(int,int){}
};
X x { abc}; //编译错误
我如何声明我想要默认的聚合初始化构造函数,就像默认的那样构造函数 X()= default
?谢谢。
没有默认的聚合初始化构造函数。
聚合初始化仅在聚合上发生。除其他外,聚合是没有(用户提供的)构造函数的类型。
做您想做的正确方法是使工厂函数以您特殊的方式构造您的类型。
这样,类型可以保持聚合,但是有一种简便的方式可以按照您想要的方式对其进行初始化。
在需要时给类型构造函数强制用户调用构造函数来构造它。否则,您只需使用工厂功能。
Suppose I have a class like this:
struct X {
char buf[10];
};
X x{"abc"};
This compiles. However, if I add user defined constructors to the class, this implicitly declared aggregate initialization constructor will be deleted:
struct X {
char buf[10];
X(int, int) {}
};
X x{"abc"}; // compile error
How can I declare that I want default aggregate initialization constructor, just like that for default constructor X()=default
? Thanks.
There is no "default aggregate initialization constructor".
Aggregate initialization only happens on aggregates. And aggregates are types that, among other things, don't have (user-provided) constructors. What you're asking for is logically impossible.
The correct means of doing what you want is to make a factory function to construct your type in your special way. That way, the type can remain an aggregate, but there's a short-hand way for initializing it the way you want.
You give a type a constructor when you want to force users to call a constructor to construct it. When you don't, you just use factory functions.
这篇关于如何保留隐式声明的聚合初始化构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!