【发布时间】:2017-08-23 13:46:36
【问题描述】:
我写了这个小测试程序,问题是程序在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;
}
【问题讨论】:
-
检查你的界限。如果您开始时的数量比 26 更适中(比如一两个),您可能会注意到比预期更多的动物喋喋不休。
-
请随意写
'a'而不是97。记住不可移植的字符编码是没有意义的。
标签: c++ class pointers for-loop memory-management