c++创建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;
}
//结果为: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;
}
//结果为: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];//只能调用无参的
cout<<"========="<<endl;
delete[] t;
}
//运行结果如下
//Test contruct
//Test contruct
//Test contruct
//Test contruct
//Test contruct
//===========
//~~~~~~~~~Test
//~~~~~~~~~Test
//~~~~~~~~~Test
//~~~~~~~~~Test
//~~~~~~~~~Test
使用堆空间的原因
- 直到运行时才能知道需要多少对象空间;
- 不知道对象的生存期到底有多长;
- 直到运行时才知道一个对象需要多少内存空间。
拷贝构造函数
- 系统默认的拷贝构造函数
#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();
}
//结果为:
//Test contruct10;
//m_a=10;
//m_a=10;
//~~~~~~~~Test
//~~~~~~~Test
- 系统默认的构造函数
#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;
}*////默认构造函数只能完成浅拷贝,将形参传给自身
};
void hello(Test temp)
{
temp.show();
}
int main()
{
Test t1(10);
t1.show();
Test t2(t1)
t2.show();
hello(t1);
}
//结果为:
//Test contruct10;
//m_a=10;
//m_a=10;
//~~~~~~~~Test
//~~~~~~~Test
#include<iostream>
using namespace std;
class Test
{
int *m_a;//定义指针类型时,系统默认的拷贝构造函数已经过不去了
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)//所以要认为的重新定义
{
m_a=new int;
*m_a=*q.m_a;
}
};
int main()
{
Test t1(10);
t1.show();
Test t2(t1);
t2.show();
}
//结果为:
//Test contruct10;
//m_a=10;
//m_a=10;
//~~~~~~~~Test10
//~~~~~~~Test10