Nod*_*eJS 1 c++ overloading ostream
以下尝试运算符重载时发生错误:
#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;
}
Run Code Online (Sandbox Code Playgroud)
您必须将std::ostreamobject 作为第一个参数传递给插入运算符,<<而不是作为第二个参数,只要您以这种方式调用它:
friend void operator << (ostream &out, Dollar &dol);
Run Code Online (Sandbox Code Playgroud)
constant reference只要此函数只是打印而不打算修改对象的成员,您就应该将对象传递给插入运算符:
friend void operator << (ostream &out, const Dollar& dol);
Run Code Online (Sandbox Code Playgroud)所以通过引用传递,避免多份拷贝,const避免无意修改。
如果你想调用它以你想要的方式工作,你可以这样做:
friend void operator<<(const Dollar &dol, ostream &out){
out << dol.getDollar() << endl;
out << dol.getMarketSoums() << endl;
out << dol.getofficialSoums() << endl;
}
Run Code Online (Sandbox Code Playgroud)主要例如:
operator << (dollar, cout); // this is ok
dollar << cout; // or this. also ok.
Run Code Online (Sandbox Code Playgroud)
如您所见,我颠倒了调用插入运算符的顺序以匹配上面的签名。但我不推荐这样做,只是为了更多地了解它应该如何工作。
| 归档时间: |
|
| 查看次数: |
1244 次 |
| 最近记录: |