c++創(chuàng)建malloc
#include<iostream>
using namespace std;
class Test
{
public:
Test()
{
cout<<"Test construct"<<endl;
}
~Test()
{
cout<<"~~~~~Test"<<endl;
}
};
int main()
{
Test *t=new Test;
cout<<"========="<<endl;
delete t;
}
//結(jié)果為:Test construct
//===========
//~~~~~~~~~Test
#include<iostream>
#include<stdlib.h>
using namespace std;
class Test
{
public:
Test(int a)
{
cout<<"Test construct"<<a<<endl;
}
~Test()
{
cout<<"~~~~~Test"<<endl;
}
};
int main()
{
Test *t=new Test(5);
cout<<"========="<<endl;
delete t;
}
//結(jié)果為:Test construct5
//===========
//~~~~~~~~~Test
#include<iostream>
#include<stdlib.h>
using namespace std;
class Test
{
public:
Test(int a)
{
cout<<"Test construct"<<a<<endl;
}
Test()
{
cout<<"Test construct"<<endl;
}
~Test()
{
cout<<"~~~~~Test"<<endl;
}
};
int main()
{
Test *t=new Test[5];//只能調(diào)用無參的
cout<<"========="<<endl;
delete[] t;
}
//運(yùn)行結(jié)果如下
//Test contruct
//Test contruct
//Test contruct
//Test contruct
//Test contruct
//===========
//~~~~~~~~~Test
//~~~~~~~~~Test
//~~~~~~~~~Test
//~~~~~~~~~Test
//~~~~~~~~~Test
使用堆空間的原因
- 直到運(yùn)行時(shí)才能知道需要多少對(duì)象空間炫狱;
- 不知道對(duì)象的生存期到底有多長(zhǎng);
- 直到運(yùn)行時(shí)才知道一個(gè)對(duì)象需要多少內(nèi)存空間咽瓷。
拷貝構(gòu)造函數(shù)
- 系統(tǒng)默認(rèn)的拷貝構(gòu)造函數(shù)
#include<iostream>
using namespace std;
class Test
{
int m_a;
public:
Test(int a)
{
m_a=a;
cout<<"Test construct"<<a<<endl;
}
~Test()
{
cout<<"~~~~Test"<<endl;
}
void show()
{
cout<<"m_a = "<<m_a<<endl;
}
Test(const Test &q)
{
m_a=q.m_a;
}
};
int main()
{
Test t1(10);
t1.show();
Test t2(t1);
t2.show();
}
//結(jié)果為:
//Test contruct10;
//m_a=10;
//m_a=10;
//~~~~~~~~Test
//~~~~~~~Test
- 系統(tǒng)默認(rèn)的構(gòu)造函數(shù)
#include<iostream>
using namespace std;
class Test
{
int m_a;
public:
Test(int a)
{
m_a=a;
cout<<"Test construct"<<a<<endl;
}
~Test()
{
cout<<"~~~~Test"<<endl;
}
void show()
{
cout<<"m_a = "<<m_a<<endl;
}
/*Test(const Test &q)
{
m_a=q.m_a;
}*////默認(rèn)構(gòu)造函數(shù)只能完成淺拷貝将饺,將形參傳給自身
};
void hello(Test temp)
{
temp.show();
}
int main()
{
Test t1(10);
t1.show();
Test t2(t1)
t2.show();
hello(t1);
}
//結(jié)果為:
//Test contruct10;
//m_a=10;
//m_a=10;
//~~~~~~~~Test
//~~~~~~~Test
#include<iostream>
using namespace std;
class Test
{
int *m_a;//定義指針類型時(shí)案站,系統(tǒng)默認(rèn)的拷貝構(gòu)造函數(shù)已經(jīng)過不去了
public:
Test(int a)
{
m_a=new int;
*m_a=a;
cout<<"Test construct"<<*m_a<<endl;
}
~Test()
{
cout<<"~~~~Test"<<*m_a<<endl;
delete m_a;
}
void show()
{
cout<<"m_a = "<<*m_a<<endl;
}
Test(const Test &q)//所以要認(rèn)為的重新定義
{
m_a=new int;
*m_a=*q.m_a;
}
};
int main()
{
Test t1(10);
t1.show();
Test t2(t1);
t2.show();
}
//結(jié)果為:
//Test contruct10;
//m_a=10;
//m_a=10;
//~~~~~~~~Test10
//~~~~~~~Test10
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者