c++ - 尝试将对象数组传递给函数时出错

标签 c++ arrays argument-passing dynamic-arrays dynamic-allocation

我正在尝试传递一组 Student

进入函数 processStudent(string myFilename, Student* myArray, int &mySize)。 但它给了我不同类型的错误。

Student() 什么都不做,但我试图为它们分配某种值,它仍然给出完全相同的错误消息:

主要是我有这个:

// Create an array of students, with the size of theMax (256)
Student* arrayOfStudent= new Student[theMax];

// An integer that will keep track of actually how many students
// Because when we loop, we want to loop within the cell
// that actually have data or student.
int actualSize = 0;

// Invoke the helper function to set up the array of students
// It passed the arryOfStudent by reference, so the changes
// inside of the function will be reflected when it returns
processStudent(filename, arrayOfStudent, actualSize);

函数是这样的:

void processStudent(string myFilename, Student* myArray, int& mySize)
{
    // Something here, but removed still gives that error
}

//类(class)Student的cpp文件

Student::Student() 
{
    // Nothing here
}

错误信息:

new-host-2:csci135p1 george$ g++ -Wall -o csci135p2main csci135p2main.cpp
Undefined symbols for architecture x86_64:
  "Student::Student()", referenced from:
      _main in cc3fTXti.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status

我一直在剥离和剥离我的代码,但这个错误不会消失。我想创建这个数组,并将它传递给 processStudent 函数,这样它就可以在读取文件时设置每一个。

最佳答案

你应该问自己一些对你有帮助的问题:

“如何创建 Student 的新实例?”
好吧,我是这样做的:Student* s = new Student(); - 它创建新对象并将对它的引用存储为指针 (Student*)

“那么如何创建一个包含 10 个 Student 的数组?”
好吧,它可能是一个指向新 Student 的指针数组,我可能不得不多次调用 new ......通过这种方式思考你会很容易最终得到这样的结果:

Student** students = new Student*[10];
for (int i = 0; i < 10; ++i)
    students[i] = new Student();

... 这意味着,当你清理它时,你将不得不在每个 Student* 上调用 delete 另外你还必须清理数组本身:在 Student** 上调用 delete[] - 当你意识到丑陋的内存管理与指针数组连接时,它应该让你寻找更简单和更好的方法实现它,因此您最终应该使用 std::vector 而不是数组,如果可能的话使用对象而不是指针,如果可能的话,那么至少使用智能指针而不是裸指针。

关于c++ - 尝试将对象数组传递给函数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10142751/

相关文章:

oop - 多少个参数是一个合理的数字,大对象与原子参数。面向对象编程

c++ - 在 C++ 中重用 strftime

c++ - 如何在linux内核模式下编程编译 "Hello World"代码?

c# - 有没有办法将数组翻译成字典

javascript - 从嵌套数组中删除元素

java - 如何将数组作为注释参数传递?

c++ - 改变静态文本的颜色C++

c++ - 为字符数组C++分配额外的内存

javascript - 数组内容不在 ReactJS 中呈现

python - 为什么我的 Python 参数无法解包?