这个问题在这里已有答案:
如何在C ++中实现Java中的类对,如何在C ++中使用?
当我这样做时,我做了类似于标准库中的Map.Entry<K, V>
接口。您应该覆盖Object.equals(Object)
和Object.hashCode()
,以便键和值在逻辑上彼此相等的两对在逻辑上相等并且散列相同 - 请参阅Bloch的Effective Java的第9项,以获取有关如何执行良好实现的一些指示。
这是我做的:
@Override
public String toString() {
//same convention as AbstractMap.SimpleEntry
return key + "=" + value;
}
@Override
public boolean equals(Object o) {
if(o == this) return true;
if(!(o instanceof Pair)) return false;
Object otherKey = ((Pair<?, ?>)o).getKey();
Object otherValue = ((Pair<?, ?>)o).getValue();
return (key == null ? otherKey == null : key.equals(otherKey))
&& (value == null ? otherValue == null
: value.equals(otherValue));
}
@Override
public int hashCode() {
return 17 + 55555 * (key == null ? 72 : key.hashCode())
+ 232323 * (value == null ? 73 : value.hashCode());
}
class Pair<F,S> {
private F first;
private S second;
public Pair(F first, S second) {
this.first = first;
this.second = second;
}
public F getFirst() { return first }
public S getSecond() { return second }
}
您只需要包含正确的标题
#include <utility>
#include <string>
using std::string;
using std::makepair;
using std::pair;
void foo()
{
string hello("Hello");
float value(42);
auto p = makepair(hello, value); // or: pair<string, float> = ...
}