如何在没有硬编码的情况下在 C++ 中获取类数组的长度?

Vik*_*ngh 0 c++ arrays class

我在 C++ 中有一个类数组。我是这样定义的:

Student* pliststudent = new Student[2]{ 3,5 };
Run Code Online (Sandbox Code Playgroud)

我知道当我们将类数组分配给Student* pliststudent.

如果不对其进行硬编码,就很难提取类数组的长度。

我实现了代码,因此它不是硬编码的(使用友元函数)。但我认为,必须存在更好的解决方案。

以下是我的完整代码:

Student* pliststudent = new Student[2]{ 3,5 };
Run Code Online (Sandbox Code Playgroud)

有没有更好的解决方案?我不想硬编码 Student 类数组的大小。

Mil*_*nek 5

您无法从指向数组第一个元素的指针获取数组的长度。当数组衰减为指针时,该信息将丢失。

您需要将长度信息保存在某处,或者您自己:

int length = 2;
Student* pliststudent = new Student[length]{ 3,5 };
Run Code Online (Sandbox Code Playgroud)

或者通过使用一个为您跟踪长度的容器:

std::vector<Student> students{3, 5};
// students.size() returns the number of Student objects in the vector
Run Code Online (Sandbox Code Playgroud)

现场演示