gpt4 book ai didi

c++-cli - 托管类的成员不能是非托管类类型

转载 作者:行者123 更新时间:2023-12-03 16:04:50 33 4
gpt4 key购买 nike

我正在用 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
我怎样才能解决这个问题?

最佳答案

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

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

无论如何,您可以使用托管类型作为类成员......或使用指向 native 类型的指针作为类成员 - 不推荐使用,除非您想从 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 -> List<T>
  • std::map -> SortedDictionary<Tkey, Tvalue>
  • std::string -> String

  • 不要忘记 ^对于托管类型

    关于c++-cli - 托管类的成员不能是非托管类类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50280049/

    33 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com