我正在使用 C++ 实现大整数,我正在尝试将 cout 与我的 BigInt 类一起使用。我已经重载了 << 运算符,但它在某些情况下不起作用。
这是我的代码:
inline std::ostream& operator << (ostream &stream, BigInt &B){
if (!B.getSign()){
stream << '-';
}
stream << B.getNumber();
return stream;
}
上面的代码适用于:
c = a + b;
cout << c << endl;
但失败了:
cout << a + b << endl;
在第一种情况下程序运行良好,但在第二种情况下编译器给出错误:
main.cc: error: cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’
在这两种情况下都可以为函数重载 << 运算符吗?
方法:
string getNumber ();
bool getSign ();
string BigInt::getNumber (){
return this->number;
}
bool BigInt::getSign (){
return this->sign;
}
最佳答案
正如克里斯在评论中很快指出的那样(像往常一样),您在这里创建了一个临时文件:
cout << a + b << endl;
您不能将其绑定(bind)到非常量引用。您需要通过将 const 关键字添加到引用来更改运算符重载的签名。
此代码适用于我的虚拟 BigInt 实现(因为您尚未共享您的代码):
#include <iostream>
using namespace std;
class BigInt
{
public:
bool getSign() const { return true; }
int getNumber() const { return 0; }
const BigInt operator+(const BigInt &other) const {}
};
inline std::ostream& operator << (ostream &stream, const BigInt &B){
// ^^^^^
if (!B.getSign()){
stream << '-';
}
stream << B.getNumber();
return stream;
}
int main()
{
BigInt a, b, c;
c = a + b;
cout << c << endl;
cout << a + b << endl;
return 0;
}
但是,是的,我同意在这种特殊情况下错误消息不是不言自明的。
关于c++ - ostream 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23307043/