首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

类型转换函数,该如何解决

2013-09-05 
类型转换函数在下写了一个程序如下//Ttest.h#include iostreamusing namespace stdclass Complex{publi

类型转换函数
在下写了一个程序如下
//Ttest.h
#include <iostream>
using namespace std;
class Complex
{
public:
Complex(double r = 0,double i = 0){R = r;I = i;};
Complex(int a){R = a;I = 0;};
void print()const;
friend Complex operator+(const Complex &c1,const Complex& c2);
friend Complex operator-(const Complex &c1,const Complex& c2);
friend Complex operator-(const Complex &c1);
operator double();
private:
double R,I;
};

// Ttest.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "Ttest.h"
/*Complex::Complex(double r,double i){
R = r;I = i;
}*/
void Complex::print()const{
cout<<R<<"+"<<I<<"i"<<endl;
}
Complex operator+(const Complex& c1,const Complex& c2){
double r = c1.R+c2.R;
double i = c1.I+c2.I;
return Complex(r,i);
}
Complex operator-(const Complex& c1,const Complex& c2){
double r = c1.R - c2.R;
double i = c1.I-c2.I;
return Complex(r,i);
}
Complex operator-(const Complex& c1){
return Complex(-c1.R,-c1.I);
}
Complex::operator double(){
double a ;
a = R;
return a;
}
int _tmain(int argc, _TCHAR* argv[])
{
Complex c1(1,2);
Complex c2(3,4);
Complex c;
c = c1+c2;
c.print();
//c = 25+c2; 不知为什么只要在头文件中加入类型转换函数,这句就会出错
c.print();
c = c2 - c1;
c.print();
c = -c1;
c.print();
cout<<int(c);
return 0;
}
错误如下:
d:\backup\我的文档\visual studio 2010\projects\ttest\ttest\ttest.cpp(37): error C2666: “operator +”: 2 个重载有相似的转换
1>          d:\backup\我的文档\visual studio 2010\projects\ttest\ttest\ttest.h(9): 可能是“Complex operator +(const Complex &,const Complex &)”
1>          或       “内置 C++ operator+(int, double)”
1>          尝试匹配参数列表“(int, Complex)”时 C++ 类


[解决办法]
重载+ - 操作符和重载类型转换容易引起二义性,所以类型转换要谨慎使用。

[解决办法]

#include <iostream>
using namespace std;

class Complex
{
public:
Complex(double r = 0,double i = 0) : R(r), I(i)
{
}
friend Complex operator+(const Complex &c1,const Complex& c2);
friend Complex operator-(const Complex &c1,const Complex& c2);
friend Complex operator-(const Complex &c1);
friend std::ostream& operator<<(std::ostream& os,const Complex &c);
private:
double R,I;
};

std::ostream& operator<<(std::ostream& os,const Complex &c)
{
return os << c.R <<" + "<< c.I <<" i";
}

Complex operator+(const Complex& c1,const Complex& c2){
double r = c1.R+c2.R;
double i = c1.I+c2.I;
return Complex(r,i);
}
Complex operator-(const Complex& c1,const Complex& c2){
double r = c1.R - c2.R;
double i = c1.I-c2.I;
return Complex(r,i);
}
Complex operator-(const Complex& c1){
return Complex(-c1.R,-c1.I);
}

int main(int , char* [])
{
Complex c1(1,2);
Complex c2(3,4);
Complex c;
c = c1+c2;
std::cout << c << std::endl;
c = 25 + c2;
// 当有operator double()时, 1. 可以25转换为Complex,2. 也可以把c2转换为double 。
//这让编译器不知所措。 
//从现实上讲,把复数转换为实数通常没有意义
std::cout << c << std::endl;
c = c2 - c1;
std::cout << c << std::endl;
c = -c1;
cout<<c << std::endl;
return 0;
}

热点排行