doing5552

记录每日点滴,不枉人生一世

  C++博客 :: 首页 :: 联系 :: 聚合  :: 管理
  73 Posts :: 0 Stories :: 94 Comments :: 0 Trackbacks

公告

常用链接

留言簿(24)

我参与的团队

最新随笔

搜索

  •  

积分与排名

  • 积分 - 452042
  • 排名 - 47

最新随笔

最新评论

阅读排行榜

评论排行榜

自定义类
class arc {
……
bool operator<(const arc& b) const;

}

用容器如vector,deque存放arc对象,再其上使用stl的algrithms中的sort算法:
sort(arcVector.begin(),arcVector.end());

方法中需要使用“<”作比较操作,故需要重载operator<
简单重载 bool operator(arc&);
很可能报错:
/usr/include/c++/4.2/bits/stl_algo.h:100: 错误: no match 为‘operator<’在‘__b < __c’
主要是缺少const的限定(两个都需要)。
否则有错:
/usr/include/c++/4.2/bits/stl_algo.h:91: 错误: 将‘const arc’作为‘bool arc::operator<(const arc&)’的‘this’实参时丢弃了类型限定

分析知道linux中stl下对C++的类型安全约束很强,const保证导入对象和自身对象都不能被修改。
而stl的sort操作确实不需要修改比较的对象,也不应该被修改,故强制使用的自定义operator<需要两个const限制比较的两个对象。

使用friend方法:
friend bool operator<(const arc&, const arc&);

两种错误:
1.friend bool operator<(const arc&, const arc&) const;
错误: non-成员函数‘bool operator<(const arc&, const arc&)’不能拥有 cv 限定符

2.bool operator<(const arc&, const arc&) [const]
错误: ‘bool arc::operator<(const arc&, const arc&) const’带且仅带 1 个实参
posted on 2011-02-15 17:32 doing5552 阅读(2460) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理