Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating 2-d array of objects with a constructor with a parameter

Tags:

c++

I'm trying to create a 2-d array of objects. I'm trying to set the constructor of the class I made equal to a constructor that will take in a parameter. However, I keep getting an error saying:

main.cpp:18:37: error: invalid user-defined conversion from 'test*' to 'const test&'

int main()
{
  test arr[9][9];
  char s[9][9];
  int integerArray[9][9];
  for(unsigned int i = 0; i < 9; i++)
  {
    for(unsigned int j = 0; j < 9; j++)
    {
      cin >> s[i][j];
      arr[9][9] = new test(s[i][j]);
    }
  }
  return 0;
}

With test being the class. Can anyone help me figure out this error? I understand that the new function returns a void pointer but how can I get it so that my 2d array takes in the parameter?

Thanks.

like image 668
user1567909 Avatar asked Sep 23 '26 22:09

user1567909


1 Answers

Your 2d array is not an array of pointers to a test object. Memory is allocated for your 2d array anyway. So no need for the loop.

Unless you change your declaration

test arr[9][9];

to something like:

 test*** arr = new (test**)[rows];


  for(unsigned int i = 0; i < 9; i++)
    {
      for(unsigned int j = 0; j < 9; j++)
      {
         cin >> s[i][j];
         arr[i][j] = new test(s[i][j]);
      }
     }
like image 146
Lews Therin Avatar answered Sep 26 '26 14:09

Lews Therin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!