Search code examples
winformsc++-clistdvector

C++/CLI Winforms. E2244 "a member of the managed class cannot belong to the unmanaged class type"


Im learning c++ for now and trying to create a vector of custom data type Employee.

Employee.h code:

public ref class Employee {
public:
    System::String^ name;
    int age;
    Employee() {
        name = "";
        age = 0;
    }
    Employee(System::String^ n, int a) {
        name = n;
        age = a;
    }
};

Employee.cpp code:

#include "Employee.h"
#include <string>

int main() {
    std::vector<Employee^> employees;

    employees.push_back(gcnew Employee("Alice", 20));
    employees.push_back(gcnew Employee("Bob", 22));

    return 0;
}

When i was tried to initialize vector<Employee> in MyForm.h, like this:

private: std::vector<Employee^> Employees;

There is happening error on " ^ " : E2244 a member of the managed class cannot belong to the unmanaged class type.

I tried using different pointers, as well as creating a copy constructor for the Employee class (I tried to find similar situations with other people), but this caused even more errors. Perhaps the mistake is trivial and simple, but unfortunately I don't have much time to dive into the theory. What am I doing wrong and how can I fix it? I will be very glad if you can explain in detail.


Solution

  • C++ and C++/CLI are different languages:
    C++/CLI is the .NET version of native C++.

    You cannot use a native C++ container like std::vector to hold .NET objects like your Employee.

    Instead you should use a C++/CLI (i.e. .NET) container.

    One such cadidate is System::Collections::Generic::List, as it it somewhat similar to std::vector, with a continous memory layout for the elemenets, and random access to them.

    In your case it will be:

    System::Collections::Generic::List<Employee^> ^ employees = 
                          gcnew System::Collections::Generic::List<Employee^>();
    employees->Add(gcnew Employee("Alice", 20));
    employees->Add(gcnew Employee("Bob", 22));