Gon*_*era 3 c++ inheritance vector operator-overloading
我正在尝试实现从vector继承的类的比较运算符。
我希望它先比较自己的新属性,然后再使用从vector继承的运算符。这是一个例子:
struct A : vector<int> {
int a;
bool operator==(const A& other) {
return a == other.a && vector::operator==(other);
}
}
Run Code Online (Sandbox Code Playgroud)
但我收到此错误:
no member named 'operator==' in 'std::__1::vector<int, std::__1::allocator<int> >'
Run Code Online (Sandbox Code Playgroud)
与STL中其他类的结果相同,但如果我从自己的另一个类继承,则效果很好。
这是我正在使用的vector的实现:
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());
}
Run Code Online (Sandbox Code Playgroud)
我做错了什么?
vector的equals运算符是一个非成员函数,这意味着您不能这样调用它。您最好执行以下操作:
struct A : std::vector<int> {
int a;
bool operator==(const A& other) {
vector const& self = *this;
return a == other.a && self == other;
}
};
Run Code Online (Sandbox Code Playgroud)
但是,我不建议从标准容器中继承。相反,您应该有一个std::vector<int>数据成员(组成继承)。