【问题标题】:c++ class inheritance and operator overloading; do operator overloads get inherited?c++ 类继承和运算符重载;运算符重载会被继承吗?
【发布时间】:2011-12-05 23:58:33
【问题描述】:

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

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]

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

【问题讨论】:

  • 不是您问题的完整答案,但此类运算符应作为非成员函数实现。那将(解决您的问题(并在其他一些方面表现得更好)
  • @jalf:还有it happened again.
  • 但至少它以一种新的方式发生了。通常是您忘记关闭括号。这次我添加了一个(,这绝对没有任何意义!

标签: c++ templates inheritance operator-overloading


【解决方案1】:

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

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

应该是

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

因为您尝试与临时比较,它只能绑定到 const 引用。

【讨论】:

  • 谢谢,这清除了它!编写了太多的 Java 而没有足够的 C++,所以我似乎经常忘记 const 引用/声明......
猜你喜欢
  • 2012-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多