私はこの小さなテストプログラムを書いていますが、問題はプログラムが終了し、forループの後でクラッシュすることです。誰かが原因を説明することはできますか?私は動物が26匹が C++反復処理後のオブジェクトの破損に関する問題
- を達成したい何
各動物オブジェクトの名前
- デストラクタを呼び出すことによって割り当てられたすべてのメモリを削除する あなたはどのリード境界の外にアクセスしている
-
for (int i = 0; i < numberAnimals; i++, test++)
から
ソース
#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よりも適度な量(1つか2つのようなもの)で始めるなら、あなたはおそらく、予想以上の動物チャッターに気づいたでしょう。 – molbdnilo
そして '97 'の代わりに' 'a''を書いてください。不可能な文字エンコーディングを覚えておく必要はありません。 – molbdnilo