C/C++运算符进阶

  1、转换运算符:一种特殊的类成员函数。定义该运算符后,编译器将在可以使用内置转换的地方自动调用它

class SmallInt
{
public:
    SmallInt(int i = 0) : m_val(i)
    {
        if (i < 0 || i > 255)
            throw std::out_of_range("Bad SmallInt initializer");
    }

    // 转换函数必须是成员函数,通常定义为const
    operator int() const { return m_val; }
private:
    std::size_t m_val;
};

int main()
{
    SmallInt si(12);
    double dval = 4.5;

    // si转换成int,再转换成double
    if (si >= dval) {}
    // si转换成int,再转换成bool
    if (si) {}
    cout << si << endl; // si转换成int
    // 3.541先被转换成int,再用int构造SmallInt对象
    SmallInt si2 = 3.541;
    int ival = static_cast<int>(si2) + 3; // 显式转换

    return 0;
}

  另外,“语言只允许一次类类型转换”。比如,对于Base1 b1(可转换为int)、Base2 b2(可转换为Base1)、Base3 b3(可转换为Base2),有:

  1)b1 = b3; 不允许,需要借助转换运算符进行两次隐式的类类型转换;

  2)b1 = (Base2)b3; 允许,其中一次类类型转换是我们显式指定的;

  3)double d = b1; 允许,其中一次类型转换是借助语言内置的转换功能完成的。

  参考资料:

  《C++ Primer》

不断学习中。。。

原文地址:https://www.cnblogs.com/hanerfan/p/5136038.html