我想使用一个类作为std :: map中的键。
std::map<Type, value> collection;
Run Code Online (Sandbox Code Playgroud)
尽管我定义了operator<,但密钥不被接受:Invalid operands to binary expression ('const Type' and 'const Type')。
class Type {
public:
inline bool operator< (const Type& rhs) { /* ... */ }
Run Code Online (Sandbox Code Playgroud)
为什么会这样呢?
您必须定义operator<为
inline bool operator< (const Type& rhs) const { /* ... */ }
Run Code Online (Sandbox Code Playgroud)
因为地图在const key内部存储。
扩大一点,我也建议(就像dyp在注释中已经做过的那样)在可能的情况下使用非成员运算符重载。它们有很多优点。我不会在这里列出它们,因为已经有很多关于优点/区别的信息,让我将您链接到运算符重载:成员函数与非成员函数?。
| 归档时间: |
|
| 查看次数: |
978 次 |
| 最近记录: |