c++转换运算符没有更好的候选者
#include <iostream>
#include <string>
using namespace std;
class test {
private:
std::string strValue;
int value;
public:
test():value(0) { };
test(int a):value(a) { };
test(std::string a):strValue(a) { };
~test(){};
operator int () { return value; }
operator const char* () { return strValue.c_str(); }
};
int main() {
test v1(100);
cout << v1 << endl;
return 0;
}
当我使用 gcc 运行上面的代码时,我收到一条错误,指出没有候选者更适合转换。它们不是独占类型吗?
#include <iostream>
#include <string>
using namespace std;
class test {
private:
std::string strValue;
int value;
public:
test():value(0) { };
test(int a):value(a) { };
test(std::string a):strValue(a) { };
~test(){};
operator int () { return value; }
operator const char* () { return strValue.c_str(); }
};
int main() {
test v1(100);
cout << v1 << endl;
return 0;
}
When I run the above, with gcc I get an error saying no candidate is better for conversion.. Aren't they exclusive types?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
std::ostream
有许多operator<<
重载,包括以下两个:您的
test
类可转换为const char*
和int
。编译器无法选择要使用的转换,因为这两种转换效果同样好。因此,转换是不明确的。std::ostream
has numerousoperator<<
overloads, including both of the following:Your
test
class is convertible to bothconst char*
and toint
. The compiler can't select which conversion to use because both conversions would work equally well. Thus, the conversion is ambiguous.测试 v1(100);
计算<< v1 <<结束;
由于 cout 没有运算符 << (ostream&, test) 它尝试转换。您提供了两个,两种类型都是用 ostream 定义的,所以您有歧义。
test v1(100);
cout << v1 << endl;
Since cout doesn't have operator << (ostream&, test) it tries conversions. You provided two, both types are defined with ostream, so you got ambiguity.