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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP