日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++重载一些需要注意的地方

發布時間:2024/4/17 c/c++ 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++重载一些需要注意的地方 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1:

? 我一般習慣于把<<操作符重載成friend函數

? ?class station

{

public:

string m_info;

station(string info):m_info(info){cout<<"construct!"<<endl;};

~station(){cout<<"destruct!"<<endl;};

friend ostream &operator <<(ostream &os,station & sta);

};

ostream &operator <<(ostream &os,station & sta)

{

cout<<sta.m_info;

return os;

}


這樣子寫是可以的


2:

? ?將自定義類型存放于set等STL容器中時 需要重載<操作符


這里需要注意格式:

class station

{

public:

string m_info;

station(string info):m_info(info){cout<<"construct!"<<endl;};

~station(){cout<<"destruct!"<<endl;};

friend ostream &operator <<(ostream &os,station & sta);

   bool operator <(const station &temp)const ? ? ? ? ? ? ? ?//這里需要注意了 !

{

return this->m_info.compare(temp.m_info);

}

};

我剛開始寫的是?

bool operator <(station &temp)

{

return this->m_info.compare(temp.m_info);

} ?

結果無法編譯通過

報錯: error: no match for 'operator<' in '__x < __y'

這里 ?我想 set等STL容器在使用<的重載函數聲明 時 聲明的就是 bool operator < (const TYPE &) const; ?

集成的時候顯然也要符合要求

如果只是自己使用:

class station

{

public:

string m_info;

station(string info):m_info(info){cout<<"construct!"<<endl;};

~station(){cout<<"destruct!"<<endl;};

friend ostream &operator <<(ostream &os,station & sta);

bool operator <(station &temp)

{

return this->m_info.compare(temp.m_info);

}

};

station a("wangshuai");

station b("minhua");

cout<<(a<b)<<endl;

則顯然不需要這種函數聲明?

3:

set <station*>的話 其實不需要重載<運算符

因為它是按照指針的大小(業績指針在內存中的位置)比較的。。。

      set<station *> stationList;

stationList.insert(new station("cantaloupes"));

stationList.insert(new station("orange"));

stationList.insert(new station("apple"));

stationList.insert(new station("banana"));

stationList.insert(new station("grapes"));

stationList.insert(new station("grapes"));

for(set<station* >::iterator itor= stationList.begin();itor!=stationList.end();itor++)

{

cout<<*(*itor)<<" "<<*itor<<endl;

}

orange 0x330f48

apple 0x330f98

banana 0x330fe8

grapes 0x331038

grapes 0x331088

cantaloupes 0x332f80


4:

看這篇文章吧

http://www.cppblog.com/huyutian/articles/107457.html

轉載于:https://www.cnblogs.com/wangshuai901/archive/2011/09/08/2171887.html

總結

以上是生活随笔為你收集整理的C++重载一些需要注意的地方的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。