【问题标题】:how pass array of objects to constructor c++? [duplicate]如何将对象数组传递给构造函数 C++? [复制]
【发布时间】:2018-08-04 09:23:16
【问题描述】:

我想将学生传给 group ,但我的代码不起作用 我才开始写代码,谁能解释一下它是如何工作的

//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;
}

【问题讨论】:

  • “不工作”根本没有帮助。
  • 此时您最好的选择是这些C++ books。 C++ 不能靠猜测来学习。
  • 将构造函数声明改为Group(Students *array , int size)Group(Students array[] , int size)
  • "build failed. for some reason" - 我很确定编译器会告诉你它失败的确切原因。否则你应该得到一个更好的编译器
  • 您的函数需要学生指针数组

标签: c++


【解决方案1】:

不要在 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;
}

【讨论】:

  • 为什么不使用 Group 参数的迭代器?
  • @JorgeBellón 保持简单
【解决方案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; 
}

【讨论】:

  • 代码将起作用。但我认为你的解释并不完全正确。
  • @Nicky C 哪个部分?
  • Students *array[] 不是数组,将其重新声明为 Students array[] 也不会使其成为数组。也不鼓励在 C++ 中使用原始指针。
  • 也许......但我实际上认为这个问题是重复的。将“数组”传递给函数的主题相当混乱,这样的问题经常出现。所以你可能根本不应该花时间写这么长的答案。
  • @Zebrafish 但我只写了一些 cmets。至于作为函数参数的数组,我认为应该完全禁止它们,或者至少在对指针进行隐式调整时应该有一些警告。
猜你喜欢
  • 2020-07-27
  • 1970-01-01
  • 1970-01-01
  • 2017-03-17
  • 2013-09-13
  • 2014-06-04
  • 2012-03-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多