c++类继承和运算符重载;运算符重载会被继承吗?

发布于 2024-12-09 23:20:38 字数 712 浏览 2 评论 0原文

只是一个简单的问题,如果我有一个模板类:

template <typename T>
class foo {
public:
    bool operator!=(foo& other) const {
        //...
    }

}

然后我继承所述类:

template <typename T>
class bar : public foo<T> {
    //...
}

运算符重载是否会被继承?如果没有,我将如何实现它,以便它...因为目前在我的测试类中,这会带来一个错误:

for (bar<int> i(baz); i != bar<int>(); i++) {}

++ 运算符是在 bar 类中实现的,因此可以工作,但是 !=运算符显然不是继承的。错误消息是:

error: no match for 'operator!=' in 'i != bar<int>(0u, 0u)'
note: candidate is: bool foo<T>::operator!=(foo<T>&) const [with T = int]

这几乎概括了我遇到的问题,所以我只是想知道如何继承运算符重载。

Just a quick question, if I have a template class:

template <typename T>
class foo {
public:
    bool operator!=(foo& other) const {
        //...
    }

}

And then I inherit said class:

template <typename T>
class bar : public foo<T> {
    //...
}

Does the operator overload get inherited? And if not, how would I go about implementing it so that it does... because currently in my test class, this brings up an error:

for (bar<int> i(baz); i != bar<int>(); i++) {}

The ++ operator is implemented in the bar class, so that works, but the != operator is apparently not inherited. The error message is:

error: no match for 'operator!=' in 'i != bar<int>(0u, 0u)'
note: candidate is: bool foo<T>::operator!=(foo<T>&) const [with T = int]

That pretty much sums up the problem I'm having, so I'm just wondering how I'd go about inheriting the operator overload.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风筝有风,海豚有海 2024-12-16 23:20:38

您的运算符定义不太正确:

bool operator!=(foo& other) const {
    //...
}

应该是

bool operator!=(const foo& other) const {
    //...
}

因为您试图与临时变量进行比较,临时变量只能绑定到 const 引用。

Your operator definition isn't quite correct:

bool operator!=(foo& other) const {
    //...
}

should be

bool operator!=(const foo& other) const {
    //...
}

since you are trying to compare with a temporary, which can only be bound to a const reference.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文