geeksforgeeks-059-转换操作符

如下程序:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <cmath>

using namespace std;

class Complex
{
private:
double real;
double imag;

public:

Complex(double r = 0.0, double i = 0.0) : real(r), imag(i)
{}

// magnitude : usual function style
double ()
{

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;
}

我们使用了两种不同的方法输出同样的结果。
最好不要使用这样的小技巧,最好使用指定的成员函数来进行类似的转换,