我正在用c ++ / clr编写一个程序,我需要编写词法分析器。我有这些:
std::map <std::string, int> classes = { { "keyword",0 },{ "identifier",0 },{ "digit",0 },{ "integer",0 },{ "real",0 },{ "character",0 },{ "alpha",0 } };
std::vector<std::string> ints = { "0","1","2","3","4","5","6","7","8","9" };
std::vector<std::string> keywords = { "if","else","then","begin","end" };
std::vector<std::string> identifiers = { "(",")","[","]","+","=",",","-",";" };
std::vector<std::string> alpha = { "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z" };
std::vector<std::string>::iterator iter;
所以这就是问题所在:它将classes
,ints
,keywords
e.t.c标记为错误:
a member of managed class cannot be of a non-managed class type
我该如何解决这个问题?
答案 0 :(得分:3)
我看到你正在使用C ++ / clr,所以我认为你有充分的理由。
本机类型不能是Managed类的成员。原因是机器必须知道何时销毁/解除本机代码占用的内存 - &gt;它们位于管理类中,对象被垃圾收集器破坏。
无论如何,您可以将托管类型用作类成员...或指向本机类型的指针作为类成员 - 除非您想要从Manage转换为Native或反之亦然,否则不建议使用。这是一个例子:
// compile with: /clr
#include "stdafx.h"
#include <vector>
#include <iostream>
#include <string>
using namespace System;
using namespace System::Collections::Generic;
public ref class MyClass
{
private:
//std::vector<std::string> ints; // Native C++ types can not be members of Managed class
List<String^>^ ints; // Managed types can be class members
std::vector<std::string>* native_ints; // However You can have pointer to native type as class member
public:
MyClass()
{ // Initialize lists with some values
ints = gcnew List<String^>(gcnew array<System::String^>{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }); // Managed initialization
native_ints = new std::vector<std::string>{ "a", "b", "c" }; // Native initialization
}
~MyClass()
{
delete native_ints; // Native (not Managed) memory allocation have to be deleted
}
void Print()
{
Console::WriteLine("Managed List: {0}", String::Join(", ", ints->ToArray()));
std::cout << "Native vector: " << (*native_ints)[0] << ", " << (*native_ints)[1] << ", " << (*native_ints)[2];
}
};
int main(array<System::String ^> ^args)
{
MyClass^ mc = gcnew MyClass();
mc->Print();
return 0;
}
控制台输出是:
Managed List: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Native vector: a, b, c
类型等价物:
std::vector
- &gt; List<T>
std::string
- &gt; String
不要忘记托管类型的^