C ++中的转换运算符

在本文中,我们将了解C ++中的转换运算符。C ++支持面向对象的设计。因此,我们可以将某些实际对象的类创建为具体类型。

有时我们需要将一些具体的类型对象转换为某些其他类型对象或某些原始数据类型。要进行此转换,我们可以使用转换运算符。这类似于类中的运算符重载函数。

在此示例中,我们将使用复数类。它有两个实数和虚数参数。当我们将此类的对象分配给某些双精度类型的数据时,它将使用转换运算符将其转换为其大小。

范例程式码

#include <iostream>
#include <cmath>
using namespace std;
class My_Complex {
   private:
      double real, imag;
   public:
      My_Complex(double re = 0.0, double img = 0.0) : real(re), imag(img) //default constructor{}
      double mag() {    //normal function to get magnitude
         return getMagnitude();
      }
      operator double () { //Conversion operator to gen magnitude
         return getMagnitude();
      }
   private:
      double getMagnitude() { //Find magnitude of complex object
         return sqrt(real * real + imag * imag);
      }
};
int main() {
   My_Complex complex(10.0, 6.0);
   cout << "Magnitude using normal function: " << complex.mag() << endl;
   cout << "Magnitude using conversion operator: " << complex << endl;
}

输出结果

Magnitude using normal function: 11.6619
Magnitude using conversion operator: 11.6619