C++ C++;:没有调用析构函数
在下面的代码中,调用了所有构造函数,结果与预期一致,但在“for”循环完成后,不会调用析构函数。谁能说出原因吗C++ C++;:没有调用析构函数,c++,function,constructor,destructor,new-operator,C++,Function,Constructor,Destructor,New Operator,在下面的代码中,调用了所有构造函数,结果与预期一致,但在“for”循环完成后,不会调用析构函数。谁能说出原因吗 #include <iostream> using namespace std; class Animal { private: string name; public: Animal(){cout << "Constructor called" << endl;} ~Animal
#include <iostream>
using namespace std;
class Animal
{
private:
string name;
public:
Animal(){cout << "Constructor called" << endl;}
~Animal(){cout << "Destructor called" << endl;}
void set_name(string name){this-> name =name;}
void call_name (){cout << "the letter typed is : " << name <<endl;}
};
int main(){
char c_t_car = 'A';
Animal *pDog = new Animal[26];
for(int i = 0; i <= 26; i++)
{
string s_t_name (1, c_t_car);
pDog[i].set_name(s_t_name);
pDog[i].call_name();
c_t_car++;
}
delete[] pDog;
return 0;
}
#包括
使用名称空间std;
类动物
{
私人:
字符串名;
公众:
动物(){cout,即它崩溃了
显然,这次事故发生在析构函数有机会运行之前
这可能是因为你循环了26个元素,这是第27个元素。但是你的数组只有26个元素。所以你破坏了你的内存
很可能您是想为(inti=0;i<26;i++)编写,而不是当您看到
gdb program
run
bt
f #number
p i