【发布时间】:2020-06-20 18:49:27
【问题描述】:
在下面的代码中,所有的构造函数都被调用并且结果如预期的那样,但是在“for”循环完成后没有调用析构函数。谁能说说原因?
#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;
}
【问题讨论】:
-
当您在
for循环中看到<=时,如for(int i = 0; i <= 26; i++),请仔细检查。这通常是一个错误。
标签: c++ function constructor destructor new-operator