我写了这个小测试程序,问题是程序在 for 循环后终止并崩溃。谁能解释一下是什么原因?
我想要完成的事情
- 为 Animal 对象创建指针
- 为 26 个 Animal 对象分配内存
- 将每个 Animal 对象的名称设置为字母顺序 a-z
- 显示每个 Animal 对象的名称
- 通过调用析构函数删除所有分配的内存
- 退出主程序
来源
#include <iostream>
using namespace std;
class Animal {
private:
string name;
public:
Animal() {
cout << "Animal created." << endl;
}
~Animal() {
cout << "Animal destructor" << endl;
}
void setName(string name) {
this->name = name;
}
void speak() {
cout << "My name is: " << name << endl;
}
};
int main() {
int numberAnimals = 26;
Animal *pAnimal = new Animal[numberAnimals];
char test = 97; // a
cout << "========================================================" << endl;
for (int i = 0; i <= numberAnimals; i++, test++) {
string name(1, test);
pAnimal[i].setName(name);
pAnimal[i].speak();
}
cout << "========================================================" << endl;
delete[] pAnimal;
return 0;
}
最佳答案
改变
for (int i = 0; i <= numberAnimals; i++, test++)
到
for (int i = 0; i < numberAnimals; i++, test++)
您正在越界访问,这会导致未定义的行为。
关于c++迭代后破坏对象的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45841543/