c ++迭代后破坏对象的问题

时间:2017-08-23 13:46:36

标签: c++ class pointers for-loop memory-management

我写了这个小测试程序,问题是程序终止并在for循环后崩溃。有人可以解释原因吗?

我想要完成的事

  1. 为Animal对象创建指针
  2. 为26个动物对象分配内存
  3. 将每个Animal对象的名称设置为字母顺序a-z
  4. 显示每个动物对象的名称
  5. 通过调用析构函数
  6. 删除所有已分配的内存
  7. exit main
  8. 来源

    #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;
    }
    

2 个答案:

答案 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();

    }