1.构造函数
(1)构造函数的函数名与类名相同;
(2)构造函数无返回值;
(3)对象构造时系统自动调用相应的构造函数;
(4)构造函数可以重载;
(5)构造函数可以在类内/类外定义;
(6)无参的构造函数和全缺的构造函数只能有一个。
//构造函数
#include <iostream>
#include <stdlib.h>
using namespace std;
class Date
{
public:
Date(int year = 1900, int month = 1, int day = 1)//无参构造函数
{
_year = year;
_month = month;
_day = day;
}
void Display()
{
cout << _year << "-" << _month << "-" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(1900, 1, 1);
d1.Display();
system("pause");
return 0;
}
初始化列表
//初始化列表
Date(int year = 1900,int month = 1,int day = 1)
:_year(year)
, _month(month)
, _day(day)
{}
初始化列表比函数内初始化更高效!
对于自定义类型,在初始化时系统会自动生成初始化列表(即,自定义类型,构造时会先走一遍初始化列表),然后再调用一遍函数体内的初始化,也就是初始化了两遍。可以说,初始化列表是成员变量定义的地方。
那些构造函数只能在初始化列表中初始化?(那些构造函数只能自己写,不能用系统自动生成的?)
(1)const修饰的常量,在定义时初始化;
(2)引用变量,必须在定义时初始化,且只能初始化一次;
(3)没有缺省构造函数的自定义的成员变量。
2.拷贝构造函数
(1)创建对象时使用同类进行初始化,是特殊的构造函数;
(2)拷贝构造函数其实是一个构造函数的重载;
(3)拷贝构造函数的参数必须使用引用传参,使用传值方式会引发无穷递归调用;
(4)若为显示定义,系统会默认缺省的拷贝构造函数。缺省的拷贝构造函数会依次拷贝类成员进行初始化。
//拷贝构造函数
Date(const Date& d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
void test()
{
Date d1;
Date d2(d1);
}
3.析构函数
(1)析构函数无参数,无返回值;
(2)析构函数不能重载;
(3)析构函数完成的清理工作,并不是释放空间;
(4)系统会自动生成析构函数;
(5)析构函数在类名加上字符~。
//析构函数
~Date(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
4.运算符重载
(1)增强程序的可读性;
(2)运算符重载后不能改变运算符的优先级和结合性;
(3)有5个不支持运算符重载:sizeof/::/?:/./.*
(4)拷贝构造函数是创建的对象,使用一个已有对象来初始化准备创建的对象,赋值运算符的重载是对一个已存在的对象进行拷贝赋值。
//赋值运算符重载
#include <iostream>
#include <stdlib.h>
using namespace std;
class Date
{
public:
Date()
{}
Date& operator=(const Date& d)
{
if (_year != d._year)
{
this->_year = d._year;
this->_month = d._month;
this->_day = d._day;
}
return *this;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1;
Date d2;
d2 = d1;
system("pause");
return 0;
}
5.取地址操作符重载
Date* operator&()
{
return this;
}
6.const修饰的取地址操作符重载
const Date* operator&()const
{
return this;
}
三、隐含的this指针
1. 每个成员函数都有一个指针形参,名字是固定的,称为this指针,this指针是隐式的;(构造函数比较特殊,没有隐含this形参)
2. 编译器会对成员函数进行处理,在对象调用成员函数时,对象地址作实参传递给成员函数的第一个形参this指针;
3. this指针是成员函数隐含指针形参,是编译器自己处理的,我们不能在成员函数的形参中添加this指针的参数定义,也不能在调用时显示传递对象的地址给this指针。
//隐含的this指针
void Display()
{
cout << _year << endl;
}
void Display(Date* this)
{
cout << this->_year << endl;
}