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

关于 default arguments解决办法

2012-02-08 
关于 default arguments初学C++,遇到问题,请教方家:运行下面程序,出现如下错误:errorC2679:binary+:nooper

关于 default arguments
初学C++,遇到问题,请教方家:
        运行下面程序,出现如下错误:
error   C2679:   binary   '+ '   :   no   operator   defined   which   takes   a   right-hand   operand   of   type   'const   double '   (or   there   is   no   acceptable   conversion)

把程序中第6行中的参数不设默认值又能正常运行,还请高人指点!!


//   complex   num.cpp   :   Defines   the   entry   point   for   the   console   application.
//

#include   "stdafx.h "
#include   <iostream>
using   namespace   std;

class   complex
{
public:
complex(double=0,double=0);//   line   6,default   arguments

complex(double   a)
{
real=a;
                                      }
complex*   operator+(complex   b)
{
real+=b.real;
image+=b.image;
return   this;
}
void   print()
{
cout < <real < < '\t ' < <image < <endl;
}
private:
double   real;
double   image;
};

complex::complex(double   r,double   i)
{
real=r;
image=i;
}

int   main(int   argc,   char*   argv[])
{
complex   a(1.00,2.00);
a+1.0;
a.print();
return   0;
}



[解决办法]
两个构造函数,
由于默认参数的存在,
导致歧义了 ~
[解决办法]
complex operator+(complex b)
看effective c++ 2e item 23

[解决办法]
a+1.0;

该语句需要调用 complex* operator+(complex b)
因此需要把 1.0 构造为一个complex对象,
这个时候,
complex(double=0,double=0);
complex(double a)

由于第一个构造函数带有两个默认参数,匹配 把1.0构造为一个 complex
第二个构造函数带一个参数,也匹配 把1.0构造为一个 complex,
所以歧义了 ~

热点排行