/一.this 指針:
特點:
this指針的類型是: 類類型*const
this指針並不是對象本身的一部分,不影響sizeof的結果
只能在成員函數中用(後面還有補充)
this指針式類成員函數的第一個默認隱含參數,編譯器自動維護傳遞~
classDate
{
public:
voidSetDate(intyear,intmonth,intday)
{
_year = year;
_month = month;
_day = day;
}
voidPrintDate()
{
cout<<_year<<"-"<<_month<<"-"<<_day<<endl;
}
private:
int_year;
int_month;
int_day;
};
轉到反彙編:
_year = year;
00D91613 mov eax,dword ptr [this] //將this放入eax寄存器
00D91616 mov ecx,dword ptr [year]
00D91619 mov dword ptr [eax],ecx
_month = month;
00D9161B mov eax,dword ptr [this]
00D9161E mov ecx,dword ptr [month]
00D91621 mov dword ptr [eax+4],ecx
_day = day;
00D91624 mov eax,dword ptr [this]
00D91627 mov ecx,dword ptr [day]
00D9162A mov dword ptr [eax+8],ecx
intmain()
{
Date d1, d2, d3;
d1.SetDate(2016, 9, 25);
d2.SetDate(2016, 9, 26);
d3.SetDate(2016, 9, 24);
d1.PrintDate();
d2.PrintDate();
d3.PrintDate();
cout<<sizeof(Date)<<endl;
return0;
}
//class Date
//{
//public:
// void SetDate( Date* const this,int year, int month, int day)//this指針是類成員函數的第一個默認隱含參數,編譯器自動維護傳遞, 類編寫者不能顯式傳遞。
//
//
// {
// this->_year = year;
// this->_month = month;
// this->_day = day;
// }
//private:
// int _year;
// int _month;
// int _day;
//}
_thiscall調用約定:
參數從右向左壓棧
只能在類的成員函數上*/
//二
構造函數:
//定義:是一個特殊的成員函數,名字與類名相同,創建類類型對象時,由編譯器自動調用,在對象的週期內只調用一次。
//特點:可以重載。
// 無返回值,
// 名字與類名相同
// 有初始化列表(可以不用,但是類裏面的const和引用必須在初始化列表裏面初始化!還有A類包含B類的對象,若B的對象不是缺省的構造參數,則也必須在初始化
// 列表裏面初始化);
//構造函數可以重載
//class Data
//{
//public:
// Data()
// {
// }
// Data(int year,int month,int day)//構造函數可以重載
// {
// _year = year;
// _month = month;
// _day = day;
// }
// Data(int year,int month)//構造函數可以重載
// {
// _year = year;
// _month = month;
// }
//private:
// int _year;
// int _month;
// int _day;
//};
//void Fun()
//{
//
//}
//int main()
//{
//
// Data t1(2016,13,25);
// Data t2(2016,15);
// Data t3();
//
// return 0;
//}
//三
//初始化列表:
// 以一個冒號開始,接着是一個以逗號分隔的數 據成員列表,每個數據成員後面跟一個放在園括號中的初始化式。
//
//【初始化順序】
// 1、每個成員在初始化列表中只能出現一次。
// 2、初始化列表僅用於初始化數據成員,並不指定這些數據
//成員的初始化順序,
// 數據成員在類中定義順序就是在參數列表中的初始化
//順序。
// 3、儘量避免使用成員初始化成員,成員的初始化順序最好
//和成員的定義順序保持一致。//避免出錯!
//初始化參數列表
//class Data
//{
//public:
// // Data ()
// // :_year(1),_month(2),_day(1)
// //
// //{
// // }
// Data (int year)
// :_year(1),_month(2),_day(1),ra(year)
//
// {
// }
//
// void PrintDate()
// {
// cout<<_year<<"-"<<_month<<"-"<<_day<<endl;
// }
//private:
// int _year;
// int _month;
// //int _day;
// const int _day;//必須在構造函數基/成員初始值設定項列表中初始化
// int &ra;//必須在構造函數基/成員初始值設定項列表中初始化
//};
//void Fun()
//{
// Data t;
// t.PrintDate();
//
//}
//int main()
//{
// Fun();
// getchar();
// return 0;
//}