简体   繁体   English

为什么我不能用c ++中的new调用参数化构造函数?

[英]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.

相关问题 我如何为 c++ 中分配的动态对象数组中的所有对象调用参数化构造函数? - How can i call the parameterized constructor for all objects in my dynamic array of objects on allocation in c++? 为什么我可以在C ++中调用已删除的私有构造函数? - Why can I call deleted, private constructor in C++? 为什么我不能为构造函数(C ++)指定调用约定? - Why can't I specify the calling convention for a constructor(C++)? 如何在C++中调用Base class的参数化构造函数? - How to call parameterized Constructor of Base class in C++? 为什么我不能在带有私有构造函数的c ++类中声明一个空的构造函数 - Why can't I declare an empty constructor in a c++ class that extends from one with a private constructor 为什么我不能在 C++ 中调用 max 函数? - Why I can't call max function in C++? 如何在C ++中从单个对象调用参数化和非参数化构造函数 - how to call parameterized and non parameterized constructor from single object in c++ 我不知道为什么复制构造函数的调用在 C++ 中不稳定 - I don't know why the copy constructor's call is erratic in c++ 我应该将结构用作 C++ 中的参数化构造函数吗? - Shall I use the structs as a Parameterized Constructor in C++? 为什么我不能从C ++中该类的实例调用该类的构造函数? - Why can I not call my class's constructor from an instance of that class in C++?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM