1
#include <iostream>
using namespace std;
class Complex
{
double real, imag;
public:
Complex( double r = 0, double i = 0 ) : real( r ), imag( i ) { };
operator double() const; //强制类型转换
};
Complex::operator double() const{return real;}
int main()
{
Complex c( 1.2, 3.4 );
cout << ( double ) c << endl; // static_cast<double>(c) 或 c
// 输出 1.2
double n = 2 + c; // 等价于double n = 2 + c.operator double()
cout << n; //输出 3.2
}
2
#include <iostream>
using namespace std;
class Complex
{
double real, imag;
public:
Complex( double r = 0, double i = 0 ) : real( r ), imag( i ) { };
operator double() const{ return real;}; //强制类型转换
};
int main()
{
Complex c( 1.2, 3.4 );
cout << ( double ) c << endl; // static_cast<double>(c) 或 c
// 输出 1.2
double n = 2 + c; // 等价于double n = 2 + c.operator double()
cout << n; //输出 3.2
}