Search code examples
c++-cli

C++ CLI Passing an array to class


As the title says I have to create class that can accept arrays as a parameter.

Here is my current version of the header file:

public ref class MyClass {

public:
    MyClass() {};  
    MyClass(array<int, 2> ^(&A1), const int &i2) : A1(A1), I2(i2) {};
    String^ Method(); 
    ~MyClass() {};

private: 
    array<int, 2>^ A1 = gcnew array<int, 2>(3, 3) {
        { 1, 1, 1 },
        { 1, 1, 1 },
        { 1, 1, 1 },
    };  
    int I2 = 5;  
};

String^ MyClass::Method() // Simple output for debugging 
{
    String^ OutputText;
    int sum=10;
    OutputText= "OutputText = " + sum;
    return OutputText;
}

As of now I'm getting the following error:

'$S1': global or static variable may not have managed type 'cli::array ^'

If I change my array to static I'll get:

"A1" is not a nonstatic data member or base class of class "MyClass"

Class has to have both constructors. I can accept a solution with vector, but i experience pretty much the same issues with it.


Solution

  • Here's what I meant under moving the initialization of the array to a constructor:

    public ref class MyClass {
    
    public:
        MyClass() {
            A1 = gcnew array<int, 2>(3, 3) {
                    { 1, 1, 1 },
                    { 1, 1, 1 },
                    { 1, 1, 1 },
                };  
        };  
        MyClass(array<int, 2> ^(&A1), const int &i2) : A1(A1), I2(i2) {};
        String^ Method(); 
        ~MyClass() {};
    
    private: 
        array<int, 2>^ A1;  
        int I2 = 5;  
    };