重载Typecasts C ++,它是如何工作的?

时间:2015-12-27 07:32:27

标签: c++ overloading typecast-operator

我正在通过以下链接了解该主题。 Over Loading Typecasts C++

class Cents
{
private:
    int m_nCents;
public:
    Cents(int nCents=0)
    {
        m_nCents = nCents;
    }

    // Overloaded int cast
    operator int() { return m_nCents; }

    int GetCents() { return m_nCents; }
    void SetCents(int nCents) { m_nCents = nCents; }
};

现在在我们的例子中,我们这样调用PrintInt():

int main()
{
    Cents cCents(7);
    PrintInt(cCents); // print 7

    return 0;
}

我无法理解PrintInt(cCents)如何映射到打印7并使用重载的int运算符。

1 个答案:

答案 0 :(得分:2)

重载int cast意味着当Cents变量转换为int时,它将返回m_nCents

// Overloaded int cast
operator int() { return m_nCents; }