读书人

为何operator string()不能用于隐式转

发布时间: 2012-04-12 15:46:35 作者: rapoo

为何operator string()不能用于隐式转换而operator int()就可以?
为何operator string()不能用于隐式转换而operator int()就可以?

有这样一个类:
class StringValue {
private:
string _rawValue;
public:

......

operator string() const {
return _rawValue;
}
};

StringValue sv;
cout << string(sv); // 可以输出_rowValue
cout << sv;// 编译失败,没有重载的<<接受StringValue为参数


但如果再加一个转换到int的函数
class StringValue {
private:
string _rawValue;
public:

......

operator string() const {
return _rawValue;
}
operator int() const { // 用来演示
return 0;
}
};

则语句
cout << sv;
可以编译执行,并且输出0。
似乎转换到string的转换函数不能用于隐式转换?
其他情况也显示如此,例如
string a, b;
StringValue sv;
a = b + sv;// 编译错误,没加operator int()时报无法从StringValue隐式转换到string,
// 加了operator int()后它是转成了int然后报string + int 非法
a = b + string(sv);// 正确

而operator int()就可以用于隐式转换。
int c, d;
StringValue sv;
c = d + sv;// 正确

为何operator string()与operator int()有这样的不同呢?我用的编译器:sun的CC和IBM的xlC。感谢解答。


[解决办法]
果然是CSDN上转来的。在水木上回过你了。

根本原因在于隐式转换不参与模板实参的推导。

C/C++ code
template <typename T>class A {};class StringValue {public:    operator A<int>() const {        return A<int>();    }};template <typename T>void f(A<T>) {}void f2(A<int>) {}int main(){    StringValue sv;    f(sv); // ERROR    f2(sv); // OK} 

读书人网 >C++

热点推荐