源程序:
#include <iostream>
using namespace std;
class myComplex
{
double real, imag;
public:
myComplex(double r = 0, double i = 0) :real(r), imag(i) {}
operator double(); //重载强制类型转换运算符double
};
myComplex::operator double()
{
return real;
}
int main()
{
myComplex c(1.2,-3.4); //输出1.2
cout << (double)c << endl; //等价于double n=2+c.operator double()
double n = 12 + c;
cout << n;
system("pause");
return 1;
}
运行结果: