【问题标题】:Call super operator== from a vector inherited class in C++从 C++ 中的向量继承类调用 super operator==
【发布时间】:2018-02-19 19:59:06
【问题描述】:

我正在尝试实现从向量继承的类的比较运算符。

我希望它首先比较自己的新属性,然后使用从向量继承的运算符。这是一个例子:

struct A : vector<int> {
    int a;
    bool operator==(const A& other) {
        return a == other.a && vector::operator==(other);
    }
}

但我收到此错误:

no member named 'operator==' in 'std::__1::vector<int, std::__1::allocator<int> >'

与来自 STL 的其他类的结果相同,但如果我从我自己的另一个类继承它会很好。

这是我正在使用的向量的实现:

inline _LIBCPP_INLINE_VISIBILITY
bool
operator==(const vector<_Tp, _Allocator>& __x, const vector<_Tp, _Allocator>& __y)
{
    const typename vector<_Tp, _Allocator>::size_type __sz = __x.size();
    return __sz == __y.size() && _VSTD::equal(__x.begin(), __x.end(), __y.begin());
}

我做错了什么?

【问题讨论】:

  • 你不应该从标准库容器继承
  • @P0W 除非privately? (事实并非如此,我知道)
  • std::vector 中根本没有成员 operator==。
  • 您粘贴给我们的操作员是免费操作员,而不是会员操作员 -- 所以vector::operator== 不会找到它。
  • @cdhowie 答案框在下面 ;)

标签: c++ inheritance vector operator-overloading


【解决方案1】:

vector 的相等运算符是一个非成员函数,这意味着你不能这样调用它。你最好做这样的事情:

struct A : std::vector<int> {
    int a;
    bool operator==(const A& other) {
        vector const& self = *this;
        return a == other.a && self == other;
    }
};

但是,我不建议从标准容器继承。相反,您应该有一个 std::vector&lt;int&gt; 数据成员(组合优于继承)。

【讨论】:

  • 非常好。答案是:vector const&amp; self = *this;。当你看到它时很明显,但很难弄清楚。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-24
  • 2017-12-17
  • 1970-01-01
  • 2016-07-28
  • 2017-09-05
  • 2021-09-21
  • 2011-04-09
相关资源
最近更新 更多