【发布时间】:2013-10-13 13:29:25
【问题描述】:
#include <iostream>
using namespace std;
class t{
private:
int * arr;
public:
t() { arr=new int[1]; arr[0]=1;}
t(int x) {arr=new int[1]; arr[0]=x;}
t(const t &);
~t() {cout<<arr[0]<<" de"<<endl; delete [] arr;}
t & operator=(const t & t1){arr[0]=t1.arr[0];return *this;}
void print(){cout<<arr[0]<<endl;}
};
t::t(const t & t1) {arr=new int[1];arr[0]=t1.arr[0];}
int main(){
t b=5;
cout<<"hello"<<endl;
b.print();
b=3;
b.print();
return 0;
}
为什么是结果
hello
5
3 de
3
3 de ?
为什么 "t b=5;"不会调用析构函数? “t b = 5”如何工作?它是否首先使用构造函数“t(int x)”创建一个临时对象(t类),然后使用复制构造函数“t(const t &)”创建b? 如果是这种情况,为什么它不调用 temp 对象的析构函数?
【问题讨论】:
标签: c++ constructor copy-constructor