建設(shè)銀行上海分行網(wǎng)站網(wǎng)站seo快速排名優(yōu)化的軟件
🍅
初始化和清理
拷貝復(fù)制
目錄
??1.取地址重載
??2.const取地址操作符重載
?? ?這兩個(gè)運(yùn)算符一般不需要重載,使用編譯器生成的默認(rèn)取地址的重載即可,只有特殊情況,才需要重載,比如想讓別人獲取到指定的內(nèi)容!
??1.取地址重載
class Date
{
public:Date* operator&(){return this;}private:int _year; // 年int _month; // 月int _day; // 日
};
就是取地址的操作符? ?進(jìn)行了運(yùn)算符重載..... 也很簡(jiǎn)單直接返回對(duì)應(yīng)的this指針即可,?所以直接使用編譯器默認(rèn)生成的就行
??2.const取地址操作符重載
class Date
{
public:Date* operator&(){return this;}const Date* operator&()const{return this;}
private:int _year; // 年int _month; // 月int _day; // 日
};
這里涉及到const修飾的成員函數(shù) —— const成員函數(shù)(const加在函數(shù)名的后面)
實(shí)際上他修飾的是該成員函數(shù)隱含的this指針,表示該成員函數(shù)中不能對(duì)類(lèi)的任何成員修改
class Date
{
public:Date(int year, int month, int day){_year = year;_month = month;_day = day;}void Print(){cout << "Print()" << endl;cout << "year:" << _year << endl;cout << "month:" << _month << endl;cout << "day:" << _day << endl << endl;}const void Print() const{cout << "Print()const" << endl;cout << "year:" << _year << endl;cout << "month:" << _month << endl;cout << "day:" << _day << endl << endl;}
private:int _year; // 年int _month; // 月int _day; // 日
};
void Test()
{Date d1(2022, 1, 13);d1.Print();const Date d2(2022, 1, 13);d2.Print();
}
?
可以發(fā)現(xiàn),實(shí)例化的時(shí)候加上const才會(huì)去調(diào)用const成員函數(shù)
因?yàn)檎f(shuō)到加上const(函數(shù)后),該對(duì)象的this指針被const修飾
即 對(duì)于這句代碼
const void Print() const
實(shí)際上第一個(gè)const的意思是,返回值是常量不可以被修改
第二個(gè)const屬于const成員函數(shù),修飾該對(duì)象的this指針
const void Print(const Date* this)
由于C++中權(quán)限縮小現(xiàn)象,d2對(duì)象只能調(diào)用const成員函數(shù),因?yàn)閐2被const修飾,d2中的任何成員都不能修改
const Date d2(2022, 1, 13);
可以看到,如果寫(xiě)了一個(gè)成員函數(shù)用來(lái)改變成員變量——year
d1可以 d2不行
總結(jié):
d2的this指針在實(shí)例化的時(shí)候已經(jīng)被const修飾,d2成員只有可讀屬性,所以只會(huì)去調(diào)用const成員函數(shù)——?const對(duì)象不可以調(diào)用非const成員函數(shù)(權(quán)限不能放大),只能調(diào)用const成員函數(shù)?
非const對(duì)象可以調(diào)用const成員函數(shù)(權(quán)限可以縮小),只需要調(diào)用的時(shí)候編譯器自動(dòng)在成員前加上const即可
?const成員函數(shù)內(nèi)不可以調(diào)用其它的非const成員函數(shù)嗎(權(quán)限不能放大)
非const成員函數(shù)內(nèi)可以調(diào)用其它的const成員函數(shù)(權(quán)限可以縮小)
?