1.构造函数
1.1 定义
构造函数是一个类中特殊的成员函数,名字与类名相同,创建类类型对象时由系统编译器自动调用,保证每个数据成员都有一个合适的初始值,并且在对象的生命周期内只调用一次。
1.2 特性
构造函数是特殊的成员函数,构造函数虽然叫构造函数,但是完成的初始化对象的任务,不是创建对象的任务。
1.函数名和类名相同
2.无返回值。
3.对象实例化时编译器自动调用对应的构造函数。
4.构造函数可以重载。
class Date
{
public:
Date()//无参的构造函数
{
cout << "Date()" << endl;
}
Date(int year, int month, int day)//带参的构造函数
{
_year = year;
_month = month;
_day = day;
}
void print()
{
cout << _year << '-' << _month << '-' << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1;//调用无参的构造函数
d1.print();
Date d2(2019,7,25);调用带参的构造函数
d2.print();
system("pause");
return 0;
}
注意:如果通过无参构造函数创建对象时,对象后面不需要带括号,编译会把它当成函数声明。如下所示:
int main()
{
Date d1;//调用无参的构造函数
Date d2(2019,7,25);调用带参的构造函数
Date d3();
//这句代码声明了d3函数,是一个无参函数,并且要返回一个日期类的对象。
}
5.如果类中没有显示的定义构造函数,则编译器会自动生成一个无参的默认构造函数,如果用户显示定义了编译器将不再自动生成。
class Date
{
public:
//如果用户显示定义了编译器将不再自动生成
Date(int year, int month, int day)//带参的构造函数
{
_year = year;
_month = month;
_day = day;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1;
system("pause");
return 0;
}
6.无参的构造函数和全缺省的构造函数都称为默认构造函数,并且默认的构造函数只能出现一个。
因为如果这两个都出现了,在创建对象调用构造函数时,无参的构造函数调用这两个都可以,会出现目标不明确的现象。
class Date
{
public:
Date()//无参的构造函数
{
cout << "Date()" << endl;
}
Date(int year=2019, int month=1, int day=1)//带参的构造函数
{
_year = year;
_month = month;
_day = day;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1;
system("pause");
return 0;
}
//这个代码编译器是无法编译通过的
1.3 怎样看构造函数在生命周期内只调用一次?
class Date{
public:
Date(int year,int month,int day)
{
_year=year;
_month=month;
_day=day;
cout<<"Date(int,int,int)"<<endl;
}
private:
int _year;
int _month;
int _day;
};
void TestDate()
{
Date d(2019.9.6);
}
int main()
{
TestDate();
return 0;
}
2.析构函数
2.1 定义
析构函数是特殊的成员函数
2.2 特征
1.析构函数名是在类名前加上~;
2.无参数返回值。
3.一个类有且只有一个析构函数。如果用户没有显示定义,编译器将自动生成一个默认的构造函数。
4.对象生命周期结束时,编译系统会自动调用析构函数。
#include <iostream>
#include <cstdlib>
#include <malloc.h>
#include <assert.h>
class SeqList
{
public:
SeqList(int capacity = 10)
{
_array = (int*)malloc(_capacity*sizeof(int));
assert(_array);
_capacity = capacity;
_size = 0;
}
~SeqList()
{
if (_array)
{
free(_array);
_capacity = 0;
_size = 0;
}
cout << "~SeqList()" << endl;
}
private:
int* _array;
int _capacity;
int _size;
};
void Test()
{
SeqList s;//没有析构函数时,出了作用域后在栈上的空间被释放,但是在堆上的malloc空间无法得以释放。
}
int main()
{
Test();
return 0;
}
5.编译器自动生成的默认构造函数,对会自定义成员调用它的析构函数。
#include <iostream>
#include <cstdlib>
using namespace std;
class String{
public:
String(const char* str = " ")
{
cout << "String(char* const str):" << this << endl;
if (nullptr == str)
_str = "";
_str = (char*)malloc(strlen(str) + 1);
_str = str;
}
~String()
{
cout << "~String():" << this << endl;
free(_str);
_str = nullptr;
private:
char* _str;
}
};
class Person{
//会生成默认的构造函数:将对象中_name,_gender这两个String类对象构造好
//生成默认的析构函数:将_name和_gender两个String类对象进行销毁
private:
String _name;
String _gender;
int _age;
};
void TestPerson()
{
Person p;
}
int main()
{
TestPerson();
system("pause");
return 0;
}