代码之家  ›  专栏  ›  技术社区  ›  Delano Zeke Ramdas

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

  •  0
  • Delano Zeke Ramdas  · 技术社区  · 6 年前

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

    我正在尝试创建一个包含数据类型的私有属性的类 std::string std::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 回复  |  直到 6 年前
        1
  •  1
  •   David Yaw    6 年前

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

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

    • 如果要编写托管类,请编写托管类。
      • 如果你想把这个类写成托管类( public ref class foo ),则应为其数据成员使用托管类型。如果需要使用非托管类型访问该类,请在访问器/赋值器方法中执行托管类型与托管类型之间的转换。
      • 在这种情况下 System::String^ 或者 cli::array<int>^ foo = gcnew cli::array<int>(length) List<int>^ foo = gcnew List<int>()
    • 如果要编写非托管类,请编写非托管类。
      • 如果要将该类编写为非托管类( class foo ),则应为其数据成员使用非托管类型。

    如果您发现自己一直在使用托管/非托管转换,那么可能需要将您的类作为另一个类来编写。或者考虑更改类定义,将类的职责划分为托管类和非托管类。