首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

c++ 默认的 operator== (),该如何解决

2012-03-04 
c++ 默认的 operator ()程序代码是这样的classAuthor{public:Author(){}Author(conststringstr){namest

c++ 默认的 operator== ()
程序代码是这样的
class   Author  
{
public:
Author()   {   }
Author(const   string   str)   {   name   =   str;}
bool   operator==   (const   Author&   ar)   const
{return   name   ==   ar.name;}

private:
string   name;
list <Book>   books;

ostream&   printAuthor(ostream&)   const;
friend   ostream&   operator < <   (ostream&   out,const   Author&   ar)
{return   ar.printAuthor(out);}


};
---------------------------------------
list <Author>   catalog[ 'Z '+1];
-----------------------------------
void   includeBook()  
{      
Author   autor;
Book   book;

autor.name   =   getString( "Enter   author 's   name:   ");
book.title   =   getString( "Enter   the   title   of   the   book:   ");


list <Author> ::iterator   iter   =   find(   catalog[autor.name[0]].begin(),  
catalog[autor.name[0]   ].end(),   autor);
                 
                    do_something(...)
                      .....
}
=====================================
我的问题是这样的,   iter是浏览这段链表内与autor相同的节点,   然后返回iter;
在这个find函数中两个类对象是默认的operator==   吧,   这个对比是怎么比的?
因为author类中有一个链表,   这个是怎么比较是否相等的,   还是不比较这个?
如果比较的话,   原来中的链表肯定不是空的,   而这个新建的类中的链表却是空的,   我程序测试的时候,   还是相等了..

望知道的朋友给指点一下...   谢谢

[解决办法]
相等的原因在于在Author类中定义了:
bool operator== (const Author& ar) const
{return name == ar.name;}
注意了,find使用的是iterater::value_type的operator==,此时iterater::value_type就是Author,所以find其实是使用上述这个函数来判断的,它只比较了name的相等性。
要让find同时比较name和books,就要把上述这个用户自定义的operator==注释掉,让隐式默认的operator==起作用,才能达到你所希望的结果。

热点排行