我试图弄清楚为什么当您访问std::set
命名为asdf的数组时此代码无法编译。如果没有尝试使用getItem函数,则代码将编译,但是,如果您尝试访问asdf的元素(例如本例中的索引0),则会编译该代码。编译器将抛出此错误。
main.cpp(21): error C2440: 'return': cannot convert from 'const std::set<test *,test::compare,std::allocator<_Kty>>' to 'const std::set<test *,std::less<_Kty>,std::allocator<_Kty>> &'
with
[
_Kty=test *
]
main.cpp(21): note: Reason: cannot convert from 'const std::set<test *,test::compare,std::allocator<_Kty>>' to 'const std::set<test *,std::less<_Kty>,std::allocator<_Kty>>'
with
[
_Kty=test *
]
main.cpp(21): note: No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
这是示例:
#include <set>
struct test {
int idx;
struct compare {
bool operator()(const test* a, const test* b) {
return a->idx < b->idx;
}
};
};
class asdf123 {
public:
asdf123() {
}
const std::set<test*>& getItem() const
{
return asdf[0];
}
private:
typedef std::set<test*, test::compare> stuffType[100];
stuffType asdf;
};
int main() {
asdf123 a;
return 0;
}
没有比较器,代码可以正常工作。
std::set<test*, test::compare>
并且std::set<test*>
是differnet类型,并且不能从一个隐式转换为另一个,这就是编译器抱怨的原因。
std::set
有两个默认的模板参数,因此std::set<test*, test::compare>
将
std::set<test*, test::compare, std::allocator<test*>>
并且std::set<test*>
将
std::set<test*, std::less<test*>, std::allocator<test*>>
你可能会改变的返回类型getItem()
来const std::set<test*, test::compare>&
解决这个问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句