如何将对象数组传递给构造函数c ++?

时间:2018-02-24 12:18:08

标签: c++

我想将学生转到小组,但我的代码不起作用 我只是开始编码,所以任何人都可以解释它是如何工作的

//file Group.h

class Group{

public:
    Group(Students *array[] , int size); // pointer. hard to understand

};

//main.cpp
int main() {

         int number = 9;
         Students students[number];
         Group group(students ,number) //build failed. for some reason

return 0;
}

2 个答案:

答案 0 :(得分:2)

不要在C ++中使用指针。为了上帝的爱,不要使用原始new / delete。使用std::vector

class Group
{
public:
    Group(const std::vector<Students>& v); // no pointers, easy to understand and use
};

int main()
{

         int size = 9;
         std::vector<Students> students(size);

         Group group{students}; 

return 0;
}

答案 1 :(得分:-2)

class Group
{public:
    Group(Students *array[], int size); // This is actually an "array of
                                        // pointers" to Students, not
                                        // an array of Students
};

int main()
{
    int number = 9; 
    Students students[number]; // The size of an array in standard C++ must 
                               // be a constant value. This is a variable
                               // length array issue, which C++ doesn't support

    Group group(students, number); // Build failed for three reasons. 
                   // 1) Because array size wasn't a constant value. 
                   // 2) Because the first constructor argument is the wrong type.
                   // 3) You're trying to call a constructor which has not been defined

    return 0; 
}

为了让您按照自己想要的方式工作,您需要进行三项更改:

class Group
{public:
    Group(Students array[], int size){}   // Now it's an array of Students
                                          // Also note it has squiggly
                                          // brackets after it, that means it
                                          // has a definition
};

int main()
{
    const int number = 9; // Array size is now a constant
    Students students[number];

    Group group(students, number); // Now you can call the constructor because
                                   // it's been defined

    return 0; 
}