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

posted @ 2011-09-08 22:27  王帅901  阅读(409)  评论(0编辑  收藏  举报