至少在我读到的时候,你目前的情况大致是这样的:
#include <string>
#include <map>
// defined in some other file, but class definition included via a header:
namespace library {
class Identifier {
public:
Identifier(std::string const &s) : data(s) {}
explicit operator std::string() const { return data; }
std::string data;
};
}
bool operator<(library::Identifier const &a, library::Identifier const &b) {
return a.data < b.data;
}
class Module {
std::map<library::Identifier, int> data;
public:
void insert(library::Identifier const &s, int i) {
data[s] = i;
}
};
int main() {
Module m;
library::Identifier i("foo");
m.insert(i, 1);
}
你有
Identifier
由某个库定义。在你自己的课堂上,你有一个
map
试图使用
标识符
作为关键。自从
标识符
本身没有定义
operator<
,你自己定义了一个。但它仍然没有找到,编译仍然失败,就像你没有定义一样
操作员<
完全。
我已经定义了
标识符
在名称空间内,因为我相当肯定你的代码就是这样。更重要的是,它位于名称空间中是编译器找不到也不会使用您定义的运算符的真正原因。
幸运的是,解决这个问题相当容易。您需要将运算符放在与相同的命名空间中
标识符
其本身被定义为:
#include <string>
#include <map>
// defined in some other file, but class definition included via a header:
namespace library {
class Identifier {
public:
Identifier(std::string const &s) : data(s) {}
explicit operator std::string() const { return data; }
std::string data;
};
}
namespace library {
bool operator<(library::Identifier const &a, library::Identifier const &b) {
return a.data < b.data;
}
}
class Module {
std::map<library::Identifier, int> data;
public:
void insert(library::Identifier const &s, int i) {
data[s] = i;
}
};
int main() {
Module m;
library::Identifier i("foo");
m.insert(i, 1);
}
有了这个,代码编译得很好。