我在C ++中有一个类数组。我已经这样定义它:
Student* pliststudent = new Student[2]{ 3,5 };
我知道当我们将其分配给时,类数组会衰减为一个指针Student* pliststudent
。
不对它进行硬编码就很难提取它的长度。
我实现了代码,因此未对其进行硬编码(使用朋友功能)。但我认为,必须存在更好的解决方案。
以下是我的完整代码:
class Student
{
private:
int marks;
int counter=0;
public:
Student(int marks) : marks(marks)
{}
int FinalMarks()
{
marks *=2;
return marks;
}
friend int Length(Student ob1, Student ob2);
};
int Length(Student ob1, Student ob2)
{
int i = ++ob1.counter + ++ob2.counter;
return i;
}
int main()
{
Student* pliststudent = new Student[2]{ 3,5 };
//int length = sizeof(*pliststudent) / sizeof(pliststudent[0]); //This does not work.
int length = Length(pliststudent[0], pliststudent[1]);
for (int i = 0; i < length; i++)
{
cout << (pliststudent+i)->FinalMarks() << endl;
}
return 0;
}
有更好的解决方案吗?我不想对学生类数组的大小进行硬编码。
您无法从指向数组第一个元素的指针获取数组的长度。当数组衰减到指针时,该信息将丢失。
您需要将长度信息保存在某个地方,您自己可以:
int length = 2;
Student* pliststudent = new Student[length]{ 3,5 };
或使用跟踪您长度的容器:
std::vector<Student> students{3, 5};
// students.size() returns the number of Student objects in the vector
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句