实现数组初始化器
您可以在同一行声明和初始化常规数组,如下所示:
int PowersOfTwo[] = {1, 2, 4, 8, 16, 32, 64, 128};
Is there a way to在自定义类中复制此行为?因此,例如:
MyClass<int> PowersOfTwo = {1, 2, 4, 8, 16, 32, 64, 128};
您可以让复制构造函数将数组作为其参数,但您仍然必须在上一行声明该数组。
int InitializationArray[] = {1, 2, 4, 8, 16, 32, 64, 128};
MyClass<int> PowersOfTwo = InitializationArray;
You can declare and initialize regular arrays on the same line, like so:
int PowersOfTwo[] = {1, 2, 4, 8, 16, 32, 64, 128};
Is there a way to replicate this behavior in custom classes? So, for example:
MyClass<int> PowersOfTwo = {1, 2, 4, 8, 16, 32, 64, 128};
You can have a copy constructor take an array as its parameter, but you still have to declare the array on the previous line.
int InitializationArray[] = {1, 2, 4, 8, 16, 32, 64, 128};
MyClass<int> PowersOfTwo = InitializationArray;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以以这样的方式实现您的类:
这是我的实现:
输出:
请参阅在线演示: http://www.ideone.com/CBPmj
您可以在这里看到我昨天发布的两个类似的解决方案:
使用值列表进行模板数组初始化
编辑:
您可以使用类似的技巧来填充现有的 STL 容器。例如,您可以这样写:
重载
()
和,
运算符所需的全部内容为:工作演示:http://ideone.com/0cIUD
再次编辑:
我是 享受 C++ 运算符的乐趣。现在这个:
我觉得这个看起来更好!
You can implement your class in such a way that you can write this:
Here is my implementation:
Output:
See online demo : http://www.ideone.com/CBPmj
Two similar solutions you can see here which I posted yesterday :
Template array initialization with a list of values
EDIT:
Similar tricks you can do to populate existing STL containers. For example, you can write this:
All you need to overload
()
and,
operator as:Working demo : http://ideone.com/0cIUD
AGAIN EDIT:
I'm having fun with C++ operator. Now this:
I think this looks better!
仅当您的编译器提供对 初始化程序列表的支持时才能完成此操作,C++0x 功能。
否则,必须使用其他语法,如 boost.assign 库。
This can be done only if your compiler provides support for initializer lists, a C++0x feature.
Otherwise, some other syntax would have to be used, as in the boost.assign library.