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
总结一下:
当普通类型和复合类型数据定义了相互转化的方式,在进行两种类型数据运算时需要明确指出数据类型的转换方式,否则会出现二义性。