
如下程序:
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) {} double () { return getMag(); } operator double () { return getMag(); } private: double getMag() { return sqrt(real * real + imag * imag); } }; int main() { Complex com(3.0, 4.0); cout << com.mag() << endl; cout << com << endl; }
|
我们使用了两种不同的方法输出同样的结果。
最好不要使用这样的小技巧,最好使用指定的成员函数来进行类似的转换,
近期评论