Visual C ++ CLR:使用非原始数据类型作为属性

时间:2018-04-20 14:56:41

标签: visual-c++ c++-cli clr

在Visual Studio 2013上使用Visual C ++。 项目类型:“CLR空项目”

我正在尝试创建一个包含数据类型std::stringstd::array的私有属性的类。

编译器给出了以下错误:

  

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

我所进行的研究使我相信CLR项目只允许使用原始数据类型作为类属性。
不幸的是,我一直无法找到解决方案。

错误在.h文件中给出。我复制了下面的.h文件:

{
public:

PlayableSet();
~PlayableSet();

bool verifySolutionSet(std::string solution);

std::array<int, 5> getPlayableIntegers();
std::array<char, 4> getPlayableOperators();
std::string getPlayableString();
std::array<int, 9> getPlayableSetIntegerCount();
std::array<int, 4> getPlayableSetOperatorCount();

private:

const static std::array<char, 4> OPERATOR_ARRAY ;
std::array<int, 5> PlayableIntegers;
std::array<char, 4> PlayableOperators = { '+', '-' };
std::string PlayableString = "";
std::array<int, 9> PlayableSetIntegerCount;
std::array<int, 4> PlayableSetOperatorCount = { 1, 1 }; 
}

注意:

  • 我已经包含了数组和字符串
  • 显示所有私有属性的错误。
  • PlayableOperators和PlayableSetOperatorCount仅使用前两个元素进行初始化。这是有目的的。

1 个答案:

答案 0 :(得分:1)

我的建议是,如果您要编写托管类,请编写托管类。如果您要编写一个非托管类,请编写一个非托管类。

C ++ / CLI允许混合托管代码和非托管代码,但存在限制。在编写单个类定义时,您通常希望坚持使用其中一个。

  • 如果您要编写托管类,请编写托管类。
    • 如果您要将此类编写为托管(public ref class foo),那么它应该为其数据成员使用托管类型。如果需要使用非托管类型来访问类,请在accessor / mutator方法中进行托管类型的转换。
    • 在这种情况下,这将是System::String^以及cli::array<int>^ foo = gcnew cli::array<int>(length)List<int>^ foo = gcnew List<int>()
  • 如果您要编写非托管类,请编写一个非托管类。
    • 如果您打算将此类编写为非托管(class foo),那么它应该为其数据成员使用非托管类型。

如果您发现自己一直使用托管/非托管转换,也许您需要将您的类编写为另一个。或者考虑更改类定义以将类的职责拆分为托管和非托管类。