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 <(conststation &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 的话 其实不需要重载<运算符

因为它是按照指针的大小(业绩指针在内存中的位置)比较的。。。

set 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::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

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/31950

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月8日 上午9:14
下一篇 2023年2月8日 上午9:14

相关推荐