编辑:继Mike Seymour的评论之后,我用operator char *() const;
替换operator std::string() const;
,并相应地更改了实现。这允许隐式转换,但由于某些原因,无符号long int运算符优先于char *运算符,这只是感觉不正确......另外,我不想在c类,当我有std :: string。我有一个预感,我的CustomizedInt类需要从一些东西继承,以支持我期望的功能。有没有人请详细说明Mike对std::basic_string
的评论?我不确定我是否理解正确。C++隐式转换运算符优先级
我有这样一段代码:
#include <string>
#include <sstream>
#include <iostream>
class CustomizedInt
{
private:
int data;
public:
CustomizedInt() : data(123)
{
}
operator unsigned long int() const;
operator std::string() const;
};
CustomizedInt::operator unsigned long int() const
{
std::cout << "Called operator unsigned long int; ";
unsigned long int output;
output = (unsigned long int)data;
return output;
}
CustomizedInt::operator std::string() const
{
std::cout << "Called operator std::string; ";
std::stringstream ss;
ss << this->data;
return ss.str();
}
int main()
{
CustomizedInt x;
std::cout << x << std::endl;
return 0;
}
哪个打印 “被叫运营商unsigned long int类型; 123”。我的问题是这些:
- 我删除了操作符unsigned long int后,为什么我需要明确地将x转换为std :: string?为什么不直接调用隐式转换运算符(std :: string)?
- 是否有任何文档解释哪些隐式转换被允许以及哪些是它们的优先顺序?看来,如果我将运算符unsigned int与运算符unsigned long int一起添加到此类中,则会收到关于运算符<的模糊性的编译器错误...另外,我知道定义这样的运算符可能是可怜的练习,但我不确定我完全理解相关的注意事项。有人可以请他们概述一下吗?仅仅定义公共方法ToUnsignedLongInt和ToString会更好吗?
这是相关的:[通过隐式转换为字符串流式传输对象时的重载分辨率失败](http://stackoverflow.com/questions/6677072/overload-resolution-failure-when-streaming-object-via-implicit-conversion to-str) – 2012-04-23 18:16:51
@Als:让我们慢慢来...我还没有准备好潜入模板:) – 2012-04-23 18:40:46