我写了这个小测试程序,问题是程序终止并在for循环后崩溃。有人可以解释原因吗?
我想要完成的事
来源
#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;
}
答案 0 :(得分:2)
更改
for (int i = 0; i <= numberAnimals; i++, test++)
到
for (int i = 0; i < numberAnimals; i++, test++)
您正在限制范围外访问,导致未定义的行为。
答案 1 :(得分:1)
数组元素从0到长度为1,第一个为0,最后一个为-1;在C ++中,数组中的第一个元素始终用零(不是一个)编号,最后一个元素是length-1(不是长度)
修改以下代码
for (int i = 0; i <= numberAnimals; i++, test++) {
string name(1, test);
pAnimal[i].setName(name);
pAnimal[i].speak();
}
到
for (int i = 0; i < numberAnimals; i++, test++) {
string name(1, test);
pAnimal[i].setName(name);
pAnimal[i].speak();
}