构造函数,默认构造函数和java基本一致,一旦自己创建,系统不会自动创建默认构造函数,c++对默认构造函数的定义是:
Thedefault constructor(默认构造函数)
If a constructors can becalled without parameters (it may haveparameters with default values), it is called a defaultconstructor. (默认构造函数, 不是说构造函数 一定没有参数,而是说调用时 可以不传参数。)比如:Test(int a=1,int b=2)
这个如果作为默认构造函数是可以的,我们在初始化的时候可以这样使用:
Test t;
Test t(3);
Test t(4,5);
这样调用都是可以的。
析构函数:
自己不创建系统会自动创建,函数名是 “~类名()”,如果类中有指针变量,则必须自己创建析构函数来释放资源,否则内存泄露。析构函数无返回值无参数。
#include <iostream>
using namespace std;
class Test
{
public:
Test() { cout<< "hello world"<<endl;} //函数定义写在类体内部。
//前面没有new,后面就不用delete
~Test() { cout<< "goodbye world"<<endl; }
};
int main()
{
Test t;
//对象t的生命周期,就是在main函数内。
//将在函数返回时调用析构函数。
return 0;
}
The output is:
hello world
goodbye world
#include <iostream.h>
class Test
{
public:
Test()
{
_pVar = new int[10];//手工分配内存;动态内存分配
for( int i = 0; i<10; i++)
{
_pVar[i] = i;
}
cout<< "hello world"<<endl;
}
~Test()
{
if(_pVar != NULL)//避免二次删除
{
//手工回收内存,
//以数组的形式删除指针,
//把new分配的10个整数空间全部收回。
//如果不加[]?内存泄露
delete [] _pVar;
_pVar = NULL;//指针本身置0.
}
cout<< "goodbye world"<<endl;
}
//在构造函数里new出的内存,
//一定要记得在析构函数里delete掉,
//然后指针= NULL。
void print()
{
for( int i=0; i<10; i++)
cout<<_pVar[i]<<endl;
}
private:
int * _pVar;
};
void main()
{
//Test t; //t是局部变量,本身分配在栈上。
//t的成员_pVar是个指针,里面存储的是地址。
//指针_pVar指向的new出来的堆空间,不是t的成员。
Test t1,t2,t3;
//构造函数的调用顺序:t1,t2,t3(压栈)
//析构函数的调用顺序:t3,t2,t1(出栈)先进后出。
//t.print();
}
The output is:
hello world
goodbye world
构造函数还有一个“拷贝构造函数”,用来实现深拷贝,深拷贝与浅拷贝对应。(视频第七天)
this指针,this就是指向当前对象的首地址的指针,也就是说没生成一个对象的时候,系统会自动创建一个指向对象的指针,就是this。从指针的角度去看会更容易理解,比java的还好理解,之前没学好c++才会导致java很多东西理解起来较困难!