托管类的成员不能是非托管类类型

Ana*_*oly 5 c++-cli

我正在用 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;
Run Code Online (Sandbox Code Playgroud)

所以现在的问题是:它标志着classesintskeywords等为错误: a member of managed class cannot be of a non-managed class type

我怎样才能解决这个问题?

atr*_*ski 8

我看到您正在使用 C++/clr,所以我认为您有充分的理由这样做。

本机类型不能是托管类的成员。这样做的原因是机器必须知道何时销毁/释放本机代码占用的内存->它们在管理类中,对象被垃圾收集器销毁。

无论如何,您可以使用托管类型作为类成员......或使用指向本机类型的指针作为类成员 - 不推荐使用,除非您想从 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;
}
Run Code Online (Sandbox Code Playgroud)

控制台输出是:

Managed List: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Native vector: a, b, c
Run Code Online (Sandbox Code Playgroud)

类型等价物:

并且不要忘记^托管类型