Array initialization in Managed C++

巧了我就是萌 提交于 2019-12-01 01:45:49

问题


I wish to declare and initialize a 1D managed array of items.

If it was C# code, I would write it like this:

VdbMethodInfo[] methods = new VdbMethodInfo[] {
    new VdbMethodInfo("Method1"),
    new VdbMethodInfo("Method2")
};

I am trying to write (well, actually, I'm writing a program generate) the same thing in managed C++...

So far I have:

typedef array<VdbMethodInfo^, 1> MethodArray;
// How do I avoid pre-declaring the size of the array up front?
MethodArray^ methods = gcnew MethodArray(2);
methods[0] = gcnew VdbMethodInfo("Method1");
methods[1] = gcnew VdbMethodInfo("Method2");

There are two problems with this:

  1. It's more verbose
  2. It requires me to declare the size of the array up front, which is inconvenient for my code generator

Is there an "array initialization" syntax for GC arrays in Managed C++? What is the correct syntax? Is there a good web link for this and other similar questions?


回答1:


The C++/CLI array declare & initialize syntax is not dissimilar from that in C#. Here's an example...

array<String^>^ myArray = gcnew array<String^> {"first",  "second"};



回答2:


MSDN page on managed array syntax: http://msdn.microsoft.com/en-us/library/ts4c4dw6(VS.80).aspx



来源:https://stackoverflow.com/questions/834903/array-initialization-in-managed-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!