C++ 当 符号重载 遇上 自定义类型转换 的 二义性解决(VS2019编译)

C++自定义类型数据(如复数)和普通类型数据做运算时,如果重载了‘+’号的同时,还自定义了类型转换,那么就可能遇到运算时二义性的问题;

运算符重载和自定义类型转换 如下

friend Complex  operator+(const Complex& c1, const Complex& c2);//重载‘+’号
operator double ()const ;//自定义类型转换Complex转double

二义性 解决--明确运算时数据的转换方式

      //类型转换 再加上 +号重载 运算会出现二义性,需要指明运算方式

	//运算方式一  转换为double
	f = 10.5 + (double)c + 'c';
	cout << "f=" << f << endl;


	//运算方式一  转换为Complex 结果再转换为 double
	f = (Complex)10.5 + c + (Complex)'c';
	cout << "f=" << f << endl;

先看运行结果:

f=23.5

f=133 //转为double的计算结果
f=133 //转为Complex的计算结果

n = 43

 

完整的程序

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
using namespace std;

class Complex
{
public:
	Complex(double real = 0.0, double imag = 0.0); 
	Complex& operator=(Complex& c);
	friend ostream & operator<<(ostream& out, Complex& c);
	friend Complex  operator+(const Complex& c1, const Complex& c2);//重载‘+’号
	operator double ()const ;//自定义类型转换Complex转double
private:
	double m_real;
	double m_imag;
};

void test01()
{
	Complex c1(20, 10);
	Complex c2(25.5);
	Complex c3 = c1;
	Complex c4 = Complex(100);
	Complex c5;
	
	cout << c1 << endl << c2 << endl << c3 << endl << c4 << endl << c5 <<  endl << endl;
}

void test02()
{
	//Complex c(23.5, 12.5);
	Complex c=Complex(23.5, 12.5);
	double f = c;
	cout << "f=" << f << endl;
	//类型转换 再加上 +号重载 运算会出现二义性,需要指明运算方式
	//运算方式一  转换为double
	f = 10.5 + (double)c + 'c';
	cout << "f=" << f << endl;
	//运算方式一  转换为Complex 结果再转换为 double
	f = (Complex)10.5 + c + (Complex)'c';
	cout << "f=" << f << endl;

	int n = Complex(43.2, 9.3);  //先转换为 double,再转换为 int
	cout << "n = " << n << endl;
}

int main()
{

	//test01();

	//cout << "=============================" << endl;

	test02();

	cout << endl;
	system("pause");
	return EXIT_SUCCESS;
}

Complex::Complex(double real, double imag):m_real(real), m_imag(imag)
{

}

Complex& Complex::operator=(Complex& c)
{
	this->m_real = c.m_real;
	this->m_imag = c.m_imag;
	return *this;
}

Complex  operator+(const Complex& c1, const Complex& c2)
{
	Complex tem;
	tem.m_real = c1.m_real + c2.m_real;
	tem.m_imag = c1.m_imag + c2.m_imag;
	
	return tem;
}

Complex::operator double () const
{
	return m_real;
}

ostream& operator<<(ostream& out, Complex& c)
{
	out << c.m_real << " + " << c.m_imag << "i";
	return out;
}

打开test01()和test02()的运行结果

20 + 10i
25.5 + 0i
20 + 10i
100 + 0i
0 + 0i

=============================
f=23.5
f=133
f=133
n = 43

总结一下:

当普通类型和复合类型数据定义了相互转化的方式,在进行两种类型数据运算时需要明确指出数据类型的转换方式,否则会出现二义性。

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值