C++ 转换运算符在c++;

C++ 转换运算符在c++;,c++,C++,我一直在读关于运算符重载的书,但我不明白什么是转换运算符以及它是如何有用的。有人能举例说明吗?转换运算符帮助程序员将一个具体类型转换为另一个具体类型或基元类型隐式。下面是一个例子 例如: #include <iostream> #include <cmath> using namespace std; class Complex { private: double real; double imag; public: // Default c

我一直在读关于运算符重载的书,但我不明白什么是转换运算符以及它是如何有用的。有人能举例说明吗?

转换运算符帮助程序员将一个具体类型转换为另一个具体类型或基元类型隐式。下面是一个例子

例如:

#include <iostream>
#include <cmath>

using namespace std;

class Complex
{
private:
    double real;
    double imag;

public:
    // Default constructor
    Complex(double r = 0.0, double i = 0.0) : real(r), imag(i)
    {}

    // magnitude : usual function style
    double mag()
    {
        return getMag();
    }

    // magnitude : conversion operator
    operator double ()
    {
        return getMag();
    }

private:
    // class helper to get magnitude
    double getMag()
    {
        return sqrt(real * real + imag * imag);
    }
};

int main()
{
    // a Complex object
    Complex com(3.0, 4.0);

    // print magnitude
    cout << com.mag() << endl;
    // same can be done like this
    cout << com << endl;
}
#包括
#包括
使用名称空间std;
阶级情结
{
私人:
双实数;
双imag;
公众:
//默认构造函数
复数(双r=0.0,双i=0.0):实(r),imag(i)
{}
//量值:通常的函数样式
双磁
{
返回getMag();
}
//幅值:转换运算符
运算符双()
{
返回getMag();
}
私人:
//类帮助器来获取大小
双getMag()
{
返回sqrt(real*real+imag*imag);
}
};
int main()
{
//复杂物体
复杂com(3.0,4.0);
//印刷量

你的意思是在一种类型和另一种类型之间提供转换路径的方法吗?