【问题标题】:c++ Problems with destructing objects after iterationc ++迭代后破坏对象的问题
【发布时间】:2017-08-23 13:46:36
【问题描述】:

我写了这个小测试程序,问题是程序在for循环之后终止并崩溃。谁能解释一下是什么原因?

我想要完成的事情

  1. 为 Animal 对象创建指针
  2. 为 26 个 Animal 对象分配内存
  3. 将每个 Animal 对象的名称设置为字母顺序 a-z
  4. 显示每个 Animal 对象的名称
  5. 调用析构函数删除所有分配的内存
  6. 退出主程序

来源

#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


【解决方案1】:

改变

for (int i = 0; i <= numberAnimals; i++, test++)

for (int i = 0; i < numberAnimals; i++, test++)

您正在越界访问,这会导致未定义的行为。

【讨论】:

    【解决方案2】:

    数组元素从0到length-1编号,第一个为0,最后一个为length-1;在 C++ 中,数组中的第一个元素总是用 0(不是 1)编号,最后一个元素是 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();
    
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-24
      • 1970-01-01
      • 1970-01-01
      • 2018-05-23
      • 1970-01-01
      • 2014-12-03
      • 1970-01-01
      相关资源
      最近更新 更多