【发布时间】:2014-09-27 13:37:14
【问题描述】:
'int' 和 'double' 转换函数是 'explicit' 并且在这段代码中为什么我允许使用这种转换而不是错误消息? 如果我删除所有转换重载函数代码会发生“转换错误”
class Person
{
public:
Person(string s = "", int age = 0) :Name(s), Age(age) {}
operator string() const { return Name; }
explicit operator int() const{ return 10; } // ! Explicit
explicit operator double()const { return 20; } //! Explicit
operator bool()const { if (Name != "") return true; return false; } // using this
};
int main(){
Person a;
int z = a;
std::cout << z << std::endl; // Why print "1"? Why uses bool conversion?
}
这是答案:
因为'a'不能转换成int或者double会报错,但是因为它有bool转换功能,可以转换成int,int转换成double,代码使用这个函数。
【问题讨论】:
标签: c++ type-conversion implicit-conversion