【问题标题】:C++ conversion operator overloadC++ 转换运算符重载
【发布时间】: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


    【解决方案1】:

    我更正了您所有的示例代码错误和遗漏。

    然后我将输出添加到您的隐式 operator bool() 以使其调用显而易见。

    在这里查看 coliru:http://coliru.stacked-crooked.com/a/99f4a5a9173a52a8

    int z = a;
    

    上面的行调用了隐式 bool-conversion-operator,因为这是你离开它的唯一方法,从 Personint,它只需要一个用户定义的转换(允许的最大值)。

    【讨论】:

    • 请不要将 MS-mania 类型定义和宏与标准类型混淆。它正在使用bool-conversion,因为这是您离开它的唯一允许路径。请记住:所有转换,无论使用 ctor 或 operator,都应该是 explicit,除非它们不会丢失信息。
    • "Person to int,只需要一次自定义转换。"是的。我认同。谢谢:)
    猜你喜欢
    • 1970-01-01
    • 2011-03-22
    • 1970-01-01
    • 2010-12-09
    • 1970-01-01
    • 1970-01-01
    • 2015-03-29
    • 2014-08-18
    • 1970-01-01
    相关资源
    最近更新 更多