C++ 中的转换运算符


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

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

在此示例中,我们针对复数获取一个类。它有两个参数:实部和虚部。当我们将此类的对象分配给某些 double 类型数据时,它将使用转换运算符将其转换为其幅度。

示例代码

 实际演示

#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

更新于:30-Jul-2019

2K+ 浏览

开启你的 职业

完成课程获得认证

开始
广告
© . All rights reserved.