我正在通过以下链接了解该主题。 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运算符。
答案 0 :(得分:2)
重载int cast意味着当Cents
变量转换为int时,它将返回m_nCents
// Overloaded int cast
operator int() { return m_nCents; }