質問

The last time I used C++ was before it could be managed. Recently, though, I've returned from Java to see that C++ can now be managed !

It didn't take me long to realise what gcnew and ^ were used for. However, I'm getting a little stuck with containers.

How can I create a container whose elements are managed classes of my own making? I'm looking for a similar container to STL vector.

I would like to have something like this:

List<MyClass ^> ^ mylist;

But Visual Studio returns the following errors:

Error   2   error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

Error   3   error C2238: unexpected token(s) preceding ';'

Error   1   error C2143: syntax error : missing ';' before '<'
役に立ちましたか?

解決

The last time I used C++ was before it could be managed. Recently, though, I've returned from Java to see that C++ can now be managed !

C++ cannot "be managed". You are looking here at three languages:

  1. C++ (which you are coming back to).

  2. Managed C++ (MC++) - this was the first version of the C++ altered by Microsoft into a new language, capable to work with both native code (normal C++) and the .NET platform (managed). This has been deprecated by Microsoft and replaced with C++/CX. As such, DO NOT WRITE MC++ code.

  3. C++/CX - this is the latest version of C++ altered by Microsoft for .NET interoperability. Use it when you need to write code interacting with both managed (that is, hosted/running under the .NET runtime) and un-managed code.

Either way, for your code to compile, you need a compiler switch enabling managed code (/CLR) and the following changes:

  • define your class as a C++/CX class (using ref keyword).
  • import the list from collections (you will be effectively using the .NET collections)
  • allocate everything with ref new (similar to Java and .NET).

That said, unless you are writing interop code between managed and unmanaged code using the MS .NET plarform, do not go with C++/CLI. Use C++ for unmanaged code, and C# or VB for managed code. You will be subjected to less headaches this way.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top