打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
c – 流操作符重载问题

我有一个使用运算符重载的类,但有一些警告.

// base.hclass base {public:    base();    base(int n);    virtual ~base();    virtual void printBase(std::ofstream & out);    virtual base & operator =(const base &);    friend std::ofstream & operator <<(std::ofstream & out, const base &);private:       double * coeff;       int n;};// base.cppstd::ofstream & operator<<(std::ofstream & fout, const base & obj){    for(int i =0; i<(obj.n)-1; i  )    {        fout << obj.coeff[i]<<"*x"<<i;        if(i<obj.n-2)        {            fout<<" ";        }    }    fout<<"="<<obj.coeff[(obj.n)-1];    return fout;}void base::printBase(std::ofstream & fout){    for(int i =0; i<n-1; i  )    {        fout<<coeff[i]; // warning occurs here!!        if(i<n-2)        {            fout<<" ";        }    }    fout<<"="<<coeff[n-1];}

警告是:

&GT

 warning: ISO C   says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second:    c:\wascana\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c  /bits/ostream.tcc:105:5: note: candidate 1: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(int) [with _CharT = char, _Traits = std::char_traits<char>]    ..\Hyperplane.cpp:55:17: note: candidate 2: std::ofstream& operator<<(std::ofstream&, const Hyperplane&)

从上面的警告,它应该是<<的问题.我知道原因,但我怎么能处理这个警告?谢谢!

解决方法:

问题实际上是你的一个类的构造函数:

base(int n);

这个构造函数就是所谓的转换构造函数.它可以用于将int转换为基数,因此这是合法的:

base x = 42;

如果您不想允许此隐式转换,则可以使构造函数显式:

explicit base(int n);

有趣的问题是“fout中的歧义在哪里<< coeff [i];?编译器无法决定两个候选函数(或者不应该在它们之间做出决定;您的编译器对您来说是“好的”):一个是内置的std :: ostream运算符<<重载看起来像这样:

std::ostream& operator<<(std::ostream&, double);

第二个是您的运算符重载,如下所示:

std::ofstream& operator<<(std::ofstream&, const base&);

对于第一个候选者,第一个参数需要派生到基本的转换:需要将std :: ofstream转换为std :: ostream以便调用该函数.第二个参数,一个双精度,完全匹配.

对于第二个候选者,第一个参数std :: ofstream完全匹配.第二个参数需要使用内置的double to int转换,然后使用转换构造函数将int转换为base.

为了使编译器选择一个候选函数作为要调用的正确函数,每个参数必须至少与候选者的相应参数匹配,并且匹配任何其他候选者.

在这里使用这两个候选者,第一个参数更好地匹配第二个候选者,但第二个参数更好地匹配第一个候选者,因此存在歧义.

另一种解决方案是更改重载,使第一个参数与内置候选项的第一个参数匹配:

std::ostream& operator<<(std::ostream&, const base&);
来源:https://www.icode9.com/content-4-349101.html
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
qDebug 学习小结
VC6.0中重载操作符函数无法访问类的私有成员
C++中输入输出流及文件流操作笔记
C 学习笔记之对文件的操作<2>
C++ endl 详解
Learning boost 1 Serialization
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服