Class成员函数的声明方式

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
}
posted @ 2023-11-21 16:43  conprour  阅读(10)  评论(0编辑  收藏  举报