使用运算符重载时,没有运算符"<<"匹配这些操作数
no operator "<<" matches these operands when using operator overloading
错误,
尝试运算符重载:
#include<iostream>
#include<string>
#include<ostream>
using namespace std;
class Dollar
{
private:
float currency, mktrate, offrate;
public:
Dollar(float);
float getDollar() const;
float getMarketSoums() const;
float getofficialSoums() const;
void getRates();
// In the following function I was trying to overload "<<" in order to print all the data members:
friend void operator<<(Dollar &dol, ostream &out)
{
out << dol.getDollar() << endl;
out << dol.getMarketSoums() << endl;
out << dol.getofficialSoums() << endl;
}
};
Dollar::Dollar(float d)
{
currency = d;
}
float Dollar::getDollar() const
{
return currency;
}
float Dollar::getMarketSoums() const
{
return mktrate;
}
float Dollar::getofficialSoums() const
{
return offrate;
}
void Dollar::getRates()
{
cin >> mktrate;
cin >> offrate;
}
int main()
{
Dollar dollar(100);
dollar.getRates();
// In this line I am getting the error. Could you please help to modify it correctly?
cout << dollar;
system("pause");
return 0;
}
您必须std::ostream
对象作为第一个参数传递给插入运算符,<<
而不是第二个参数,只要您以这种方式调用它:
friend void operator << (ostream &out, Dollar &dol);
- 只要
此函数只是打印而不打算修改对象的成员,就应该将传入的对象
constant reference
:friend void operator << (ostream &out, const Dollar& dol);
因此通过引用以避免多个副本和
const
避免无意修改。
如果你想调用它以让你想要的方式工作,你可以这样做:
friend void operator<<(const Dollar &dol, ostream &out){ out << dol.getDollar() << endl; out << dol.getMarketSoums() << endl; out << dol.getofficialSoums() << endl; }
在主要例如:
operator << (dollar, cout); // this is ok
dollar << cout; // or this. also ok.
如您所见,我颠倒了调用插入运算符以匹配上述签名的顺序。但我不建议这样做,这只是为了更多地了解它应该如何工作。
相关文章:
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 如何显式调用运算符<<
- 为什么COUT在朋友函数中不起作用,该功能超载了操作员&lt;&lt;这是一个iStream运算符
- C++运算符<<调用::ostream而不是std::osttream
- BOOST ::变体无法解决运算符&lt;&lt;对于STD :: Ostream
- 过载输出<<用于类的运算符,以打印其中的元组
- C++ostream:没有运算符匹配<<&应在'&'代币
- 重载运算符<<:此运算符函数的参数太多
- C++继承运算符<<
- 重载运算符<<用于模板类.即使使用好友关键字也无法获得私人会员
- 如何过载<<用于YAML::Emitter的运算符,以序列化包含另一个自定义类的向量的自定义类
- 为什么字符串流运算符<<擦除原始值
- 关于使用运算符<<为新手提供C++中的模板
- 我已经完成了<<运算符重载,但它'It’不起作用
- 重载运算符<<输出地址而不是数据成员
- 错误:没有匹配'运算符<<"在'std::cout
- 重载运算符<<用于ostream语法
- 当运算符<存在时,为什么要定义 LT?
- log4cxx访问异常,使用<<运算符和宏
- 重载<<运算符错误C2804:二进制'运算符<<'参数太多