Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mixed management in C++

I have added a class to my program and tested it. I was really surprised that there was any real errors. Here is the code:

#pragma once
#include "Iingredient.h"
#include <string>
#include <vector>

using namespace std;

ref class Recipe{
private:
    string partsName;
    vector<Iingredient> ing;
public:
    Recipe(){}

};

And here are the errors:

Error 23 error C4368: cannot define 'partsName' as a member of managed 'Recipe': mixed types are not supported c:\users\user\documents\visual studio 2010\projects\smestras2_l1\Recipe.h 10 1 file2_L1

Error 24 error C4368: cannot define 'ing' as a member of managed 'Recipe': mixed types are not supported c:\users\user\documents\visual studio 2010\projects\smestras2_l1\Recipe.h 11 1 file2_L1

I googled a bit and found out that its about managed and unmanaged code. How to fix this? Is it related with manged and unmanaged code or not? if so how?

like image 368
Povylas Avatar asked Dec 01 '22 00:12

Povylas


2 Answers

I agree with others: you shouldn't use C++/CLI in most circumstances, you should use C# (or another "normal" managed language) for that (assuming you want to write a .Net application). C++/CLI is useful mostly in special circumstances, like interoperating between managed and unmanaged code.

If you're sure you want use C++/CLI, you can't put native classes into managed ones. But you can put pointers to native classes there:

ref class Recipe{
private:
    string* partsName;
    vector<Iingredient>* ing;
};

The code above works. But you have to keep in mind that those are normal native C++ pointers and that means you have to manually delete them. To do that property, you should read about how destructors and finalizers work in C++/CLI.

like image 169
svick Avatar answered Dec 22 '22 08:12

svick


When defining ref class Recipe, you made it managed. But std::string and std::vector are umanaged types. You are trying to declare native variables in managed class, but it is not allowed.

Seems, you are novice in C++. Just, don't use C++/CLI. Consider C#, if you target .Net or unmanaged C++.

like image 22
Lol4t0 Avatar answered Dec 22 '22 08:12

Lol4t0