[英]Why can't I call a parameterized constructor with new in c++?
If you know the issue, 如果你知道这个问题,
Assume I have a class A whose CTOR receives an integer; 假设我有一个其CTOR接收整数的A类;
I cannot do the following : 我做不到以下事情:
A* arr = new A[3](A(2), A(3), A(5));
Or any other way to initialize several members of an array. 或者任何其他方式来初始化数组的几个成员。 I read around, its just not possible.
我四处看看,这是不可能的。
My question is why, why can I do 我的问题是为什么,我为什么要这样做
A arr[3] = {A(1), A(2), A(3)};
but I can not do the above? 但我不能做到以上? Memory-wise or whatever.
记忆方面或其他什么。
Thank you very much! 非常感谢你!
The reason you can't do this in current standard C++ (referred to as C++03) is historical. 在当前标准C ++(称为C ++ 03)中无法做到这一点的原因是历史性的。 This will be cleaned up in the upcoming C++ standard (currently expected to be released this year, which would make it C++11), which will introduce what's called "uniform initialization syntax".
这将在即将推出的C ++标准中进行清理(目前预计将在今年发布,这将使其成为C ++ 11),这将引入所谓的“统一初始化语法”。
According to Stroustrup's C++0x FAQ , you can then write 根据Stroustrup的C ++ 0x FAQ ,你可以写
A* p = new A[3] {A(1), A(2), A(3)};
There's a pretty good chance your compiler is actually already supporting this. 你的编译器实际上已经很好地支持了这一点。
I believe you are trying to do "uniform initialization" which is included in C++0x. 我相信你正在尝试进行“统一初始化”,它包含在C ++ 0x中。 I don't get why the initialization list uses
A(int)
parts, I'd just do this (which is accepted by C++98/03: 我不明白为什么初始化列表使用
A(int)
部分,我只是这样做(这是C ++ 98/03接受的:
A arr[3] = {1, 2, 3};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.