gpt4 book ai didi

c++ - 用指向自定义类的指针填充数组。 C++

转载 作者:行者123 更新时间:2023-11-27 23:36:19 25 4
gpt4 key购买 nike

考虑下面的代码。在这里,我尝试创建一个数组,该数组支持接收指向 Person 类型对象的指针。我希望它的大小为 3,所以我在 [ ] 中放了一个 3。然而,这 3 似乎什么都不做。所以我想知道声明数组的正确方法是什么?正如您从下面的行中看到的那样,我可以将地址放在数组的第 23 个位置。我认为这有点奇怪,因为没有保留内存。

#include <iostream>
class Person {
//some code
};

int main() {
Person person1;

Person* array_of_person[3];
array_of_person[22] = &person1;
for (int i = 0; i < 10; i++) {
std::cout << array_of_person[i] << "hey im out of bounds " << std::endl;
}
}

最佳答案

However this 3 seem to do nothing.

3 表示:您声明了一个大小为 3 的数组。

您的其余代码是越界访问此数组的未定义行为。我假设您希望得到一些错误或其他东西。这不是 C++ 的工作方式。如果你做错了什么,错误的事情就会发生。当您的代码具有未定义的行为时,编译器不会强制发出错误。顾名思义,您的代码的作用是未定义的。

如果您需要一些反馈,请使用 vector 及其 at 方法,如:

#include <iostream>
class Person {
//some code
};

int main() {
Person person1;
std::vector<Person> array_of_person(3);

array_of_person.at(22) = person1; // out-of-bounds exception
for (int i = 0; i < 10; i++) {
std::cout << array_of_person.at(i) << "hey im out of bounds " << std::endl;
// more out-of-bounds exceptions starting from index 3
}
}

不清楚为什么要使用指针,不要在没有必要的时候使用。

关于c++ - 用指向自定义类的指针填充数组。 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58982893/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com