我有一个URL类,它重载了==,<!> lt;,<!> gt;和!=运算符以进行简单比较。 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();
}

页面操作符代码:

bool Page::operator ==(Page & p) const {
    //url is the URL instance variable of the Page class
    return url == p.GetURL();
}

这会产生如下错误:

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

我预测,我忘记这是一件愚蠢的事。你会证明我是对的吗?

编辑:Const正确性让我陷入了困境。谢谢你的帮助。

有帮助吗?

解决方案

应该是:

bool URL::operator ==(const URL & u) const {
    //url is the string instance variable
    return url == u.GetURL();
}

类似于其他运营商。

如果您仍然遇到编译器错误,也许您还没有使用GetURL() const:

std:string URL::GetURL() const {
    // whatever...
}

其他提示

我还想指出,方法(即公共接口)可以保护外部实体免受实现细节的变化。此外,一个类自动成为自己的朋友(出于同样的原因),因此只访问另一个对象的成员就可以了。

bool URL::operator ==(URL & u) const {
    //url is the string instance variable
    return url == u.GetURL();
}

可以写成:

bool URL::operator ==(URL & rhs) const
{
    return url == rhs.url;  // No need to use GetURL()
}

在我看来,这使得代码更清晰(但这又是一种意见,你的口味可能会有所不同)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top