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++重载一些需要注意的地方的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: effective C++ 读书笔记(0
- 下一篇: Silverlight WCF RIA服