如何解决std:hash 可以访问类的私有成员
我想散列一个有两个私有成员的类,例如:
foo.h
class Foo {
private:
std::string a;
std::string b;
public:
Foo (std::string a,std::string b);
bool operator==(const Foo& other) const;
bool operator!=(const Foo& other) const;
std::size_t operator()(const Foo& ) const;
};
namespace std {
template <> struct hash<Foo> {
std::size_t operator()(const Foo& cp) const;
};
}
foo.cpp
Foo::Foo (std::string _a,std::string _b) {
this->a = _a;
this->b = _b;
}
bool Foo::operator== (const Foo& other) const {
return this->a == other.a && this->b == other.b;
}
bool Foo::operator!= (const Foo& other) const {
return !operator==(other);
}
std::size_t std::hash<Foo>::operator()(Foo const& foo) const {
std::string f = foo.a; // << This wont compile!
return 1;
}
在 C++ 中,当最终的散列函数无法访问 foo 的私有成员时,通常如何对 Foo
进行散列。
随意在你的答案中加入提升或下降。
解决方法
您可以做的是将 return filter ? refined.filter(a => a.toLocaleLowerCase().includes(this.filter)) : null;
声明为 std::hash<Foo>
的 friend
:
Foo
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。