C++转换运算符过载
问题描述:
'int'和'double'转换函数是'显式',并且在此代码中为什么我允许使用此转换而不是错误消息? 如果我删除所有我的转换过载功能代码中出现的转换错误“C++转换运算符过载
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?
}
我这是答案:
因为“一”不能被转换成int或double它出现的错误,但由于它具有bool转换功能,它可以将int和int转换为double,代码使用这个函数。
答
我更正了所有的示例代码错误和遗漏。
比我添加输出到您的隐含operator bool()
使其调用显而易见。
见这里coliru:http://coliru.stacked-crooked.com/a/99f4a5a9173a52a8
int z = a;
上面一行调用隐含布尔转换运营商,因为这只是你离开它摆脱Person
到int
的方式,只需要一个用户定义的转换(允许的最大值)。
And ...为什么这段代码使用'BOOL'转换? – 2014-09-27 13:53:33
请不要将MS-mania typedefs和宏与标准类型混淆。它使用'bool'-转换,因为这是你留下的唯一允许的路径。请记住:所有转换,无论使用ctor还是“operator”,都应该是“明确的”,除非它们不会丢失信息。 – Deduplicator 2014-09-27 13:57:11
“人员为int,只需要一次用户定义的转换。”是。我想是这样。谢谢 :) – 2014-09-27 14:00:22