由于某种原因,在main func。中创建一个对象后,析构函数会立即被调用,它是否应该仅在main完成时被调用?感谢
代码:
#include <iostream>
#include <cstring>
#include <vector>
using namespace std;
class check{ //create class check
public:
string m_bank_name;
int m_check_number;
int m_branch_number;
char* m_check_sum;
check ( string bank_name, int check_number, int branch_number, char* check_sum){
int a_size = (strlen(check_sum)+1);
m_check_sum = new char[a_size]();
for (int i=0;i<a_size;i++)
{
m_check_sum[i]=check_sum[i];
}
m_bank_name= bank_name;
m_check_number = check_number;
m_branch_number = branch_number;
}
~check (){
delete [] m_check_sum;
cout<<"deleted!"<<endl;
}
};
void main(){
check ob1= check("poalim",809877,12,"4578");
cout<<ob1.m_check_sum<<endl;
getchar();
}
答案 0 :(得分:4)
此表达式
check("poalim",809877,12,"4578")
创建一个临时对象,在完整表达式(;)
之后立即被销毁在被销毁之前,它被复制到ob1
,它在主函数结束时被销毁。
也许你打算写
int main(){ //note the correct return type of main
check ob1("poalim",809877,12,"4578"); //direct constructor call
cout<<ob1.m_check_sum<<endl;
getchar();
}
我真的建议您阅读good book on C++基础知识。