jer*_*son 2 c++ compilation operator-overloading
我有一个URL类,它重载了==,<,>和!=运算符以进行简单比较.URL类具有字符串数据成员和一些作用于字符串的函数.使用URL类测试时,运算符可以正常工作.
我还有一个具有URL数据成员的Page类.我试图在Page类中重载相同的运算符.Page类中的相等性基于各自URL的相等性,因此我在比较页面时使用URL类布尔运算符.这会产生一些我无法弄清楚的编译器错误.URL运算符的代码:
bool URL::operator ==(URL & u) const {
//url is the string instance variable
return url == u.GetURL();
}
Run Code Online (Sandbox Code Playgroud)
页面操作符代码:
bool Page::operator ==(Page & p) const {
//url is the URL instance variable of the Page class
return url == p.GetURL();
}
Run Code Online (Sandbox Code Playgroud)
这会产生如下错误:
src/Page.cpp: In member function ‘bool Page::operator==(Page&) const’:
src/Page.cpp:21: error: no match for ‘operator==’ in ‘((const Page*)this)->Page::url == Page::GetURL()()’
inc/URL.h:118: note: candidates are: bool URL::operator==(URL&) const
Run Code Online (Sandbox Code Playgroud)
我预测,我忘记这是愚蠢的事情.你能证明我是对的吗?
编辑: Const正确性让我陷入了困境.谢谢您的帮助.
应该是:
bool URL::operator ==(const URL & u) const {
//url is the string instance variable
return url == u.GetURL();
}
Run Code Online (Sandbox Code Playgroud)
并且类似于其他运营商.
如果您仍然遇到编译器错误,也许您还没有创建GetURL()const:
std:string URL::GetURL() const {
// whatever...
}
Run Code Online (Sandbox Code Playgroud)