Search code examples
arraysclassvisual-c++parameterscompiler-errors

I don't know how to solve this error for passing an array into a class method


When I put the lakers roster into the lakers method parameters, it says:

error: unknown array size in delete

and

note: synthesized method 'Team::~Team()' first required here Team lakers("Los Angeles Lakers", 70, 12, lakersStartRoster)//there's an arrow pointing to the last parenthesis;

The code

    #include <iostream>
    #include <string>

    using namespace std;

    string lakersStartRoster[] = {"LeBron", "AD", "Austin", "Rui", "D'Angelo"};

    class Team {
        public:
            string name;
            int wins, losses;
            string roster[];
            Team(string x, int a, int b, string y[]){
                name = x;
                wins = a;
                losses = b;
                cout << y << endl;
            }
    };

    int main(){

        Team lakers("Los Angeles Lakers", 70, 12, lakersStartRoster);

        return 0;
    }

The Error

main.cpp:8:7: error: unknown array size in delete
        8 | class Team {
      |       ^~~~
    main.cpp: In function 'int main()':
    main.cpp:23:68: note: synthesized method 'Team::~Team()' first required here
       23 |         Team lakers("Los Angeles Lakers", 70, 12, lakersStartRoster);
          |

I got this error message on the window's powershell terminal***

I thought that I did it correctly, but I got that error message. I tried looking online for a similar problem and how to use arrays in c++, but I couldn't seem to find anything for why I'm getting this error.


Solution

  • Please refer to my comment for more details.

    Here is the code with std::vector which is an overall better implementation for beginners.

    #include <iostream>
    #include <string>
    #include <vector> // std::vector
    
    
    using namespace std;
    
    vector<string> lakersStartRoster = {"LeBron", "AD", "Austin", "Rui", "D'Angelo"};
    
    class Team {
        public:
            string name;
            int wins, losses;
            vector<string> roster{}; // note: you never set this value in your original code
            Team(string x, int a, int b, vector<string> y){
                name = x;
                wins = a;
                losses = b;
                for(string element : y) cout << element << endl; // note: you cannot just output a vector or array itself
                roster = y; // set the value here
            }
    };
    
    int main(){
    
        Team lakers("Los Angeles Lakers", 70, 12, lakersStartRoster);
    
        return 0;
    }