简体   繁体   English

数组随机存取C ++

[英]Array Random Access C++

I'm probably going to confuse myself while writing this, sorry in advance: 在写这篇文章时,我可能会迷惑自己,预先对不起:

Is there a way I can access a location in a dynamic array(increment an array pointer) of pointers using the sizeof() the object that is in the array? 有没有一种方法可以使用sizeof()数组中的对象访问动态指针数组(增加数组指针)中的位置?

For example: I have an dynamic array of type base class Student populated with derived class objects(Graduate, Undergraduate). 例如:我有一个动态类型为基类Student的数组,其中填充了派生的类对象(研究生,本科生)。

Due to this I can't just step through my array in the normal fashion to display information because the actual objects Graduate and Undergraduate are different sizes than Student. 因此,我不能仅以常规方式浏览数组以显示信息,因为研究生和本科生的实际对象与学生的大小不同。 Each array step will move sizeof(Student) when the actual objects are larger. 当实际对象较大时,每个数组步骤将移动sizeof(Student)

Depending on the type of student I am doing(this is for Graduate): 取决于我正在从事的学生类型(这是针对研究生的):

Student *student = new Graduate(undergrad, fName, lName, major, idNum, arr2, cSize, 
        degreeType, thesis);
arr[i] = student;

Where arr was declared: Student *arr = new Student[size]; 声明了arr位置: Student *arr = new Student[size];

Using my array I had created this in a for loop: 使用我的数组,我在for循环中创建了这个数组:

if (!students[i].getGradStatus()){
    handleGraduate(&students[i], i);
    step = step + sizeof(Graduate);
}
else if (students[i].getGradStatus()){
    handleUndergraduate(&students[i], i);
    step = step + sizeof(Undergraduate);
}

I was trying to come up with a way to change the step size. 我试图提出一种改变步长的方法。 I don't think this will work with a for loop but a while loop may be different. 我认为这不适用于for循环,但while循环可能有所不同。 Pretty much I'm trying to go something similar to a file seekg() but manually on an array. 我几乎在尝试类似于文件seekg()操作,但要手动对数组进行操作。

And as I've noticed everyone likes to question the use of dynamic arrays over vectors so let me just say I cannot use vectors on this project(No STL is allowed :( ). And I have to use Polymorphism, thus why I have an array pointer of type Student holding derived class objects. 正如我已经注意到的那样,每个人都喜欢对向量使用动态数组提出质疑,因此,我只能说我不能在该项目上使用向量(不允许使用STL :()。我必须使用多态性,因此为什么要使用学生类型的数组指针,其中包含派生类对象。

You can't store different sized objects in an array like that. 您不能在这样的数组中存储大小不同的对象。 When you try to copy a derived type like Graduate over a base type like Student you get what's known as slicing because of the differences in object size (parts can get chopped off). 当您尝试将派生类型(例如“ Graduate复制到“ 基本类型”(例如“ Student ,由于对象大小的差异(部分会被切掉),您将得到所谓的切片

To do this you need to store Student* (pointers to Students .) 为此,您需要存储Student* (指向Students指针。)

class Student
{
    std::string name;
public:
    Student(const std::string& name): name(name) {}
    virtual ~Student() {} // virtual destructor

    virtual void handle() = 0; // implementation must override this

    std::string get_name() const { return name; }
};

class Graduate
: public Student
{
public:
    Graduate(const std::string& name): Student(name) {}
    virtual void handle() { std::cout << "Handling Graduate" << '\n'; }
};

class UnderGraduate
: public Student
{
public:
    UnderGraduate(const std::string& name): Student(name) {}
    virtual void handle() { std::cout << "Handling UnderGraduate" << '\n'; }
};

int main()
{
    Student** students = new Student*[3];

    students[0] = new Graduate("Wendy");
    students[1] = new UnderGraduate("Bob");
    students[2] = new Graduate("Rachel");

    for(int i = 0; i < 3; ++i)
    {
        std::cout << students[i]->get_name() << '\n';
        students[i]->handle(); // polymorphic function (virtual)
    }

    delete[] students; // clean up or (better) use a smart pointer
}

Output: 输出:

Wendy
Handling Graduate
Bob
Handling UnderGraduate
Rachel
Handling Graduate

Change your array to be an array of Student pointers instead of Student objects. 将您的数组更改为学生指针而不是学生对象的数组。

 Student **arr = new Student*[size];

When you do that your objects will live on the heap and the pointer size is always the same, so the issue you are having will go away. 当您这样做时,对象将驻留在堆上并且指针大小始终相同,因此您遇到的问题将消失。

Since you can write that I assume that it's possible to instantiate a Student (non-derived). 既然可以这样写,我假设可以实例化一个Student(非派生)。 That's bad, since you're going to store derived objects in the array your students will be sliced (poor students!). 不好,因为您要将派生的对象存储在数组中,您的学生将被切片(可怜的学生!)。 To counter that you're doing weird things with the size of the instance types. 为了解决这个问题,您正在根据实例类型的大小进行操作。 Just don't. 只是不要。

Make an array of student pointers instead, Student **arr . 改用学生指针数组Student **arr Pointers have fixed size and they will point to any of the derived types of student so you don't have to worry about their sizes. 指针的大小是固定的,它们将指向任何派生类型的学生,因此您不必担心它们的大小。


Student **student = new Student*[size];
...
student[i] = new Graduate(...);

This should work. 这应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM