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;
}