我正在C++中的一个BigInt实现中工作,我试图在我的BigInt类中使用cout。我已经重载了<<操作符,但是在某些情况下它不能工作。
这是我的代码:
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;
}发布于 2014-04-26 05:40:38
正如chris在评论中所指出的那样(和往常一样),您在这里创建了一个临时的:
cout << a + b << endl;您不能将其绑定到非const引用。您需要通过将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;
}但是的,我同意在这种情况下错误信息并不是不言自明的。
发布于 2014-04-26 05:36:48
变化
inline std::ostream& operator << (ostream &stream, BigInt &B){至
inline std::ostream& operator << (ostream &stream, BigInt const& B){c可以用于BiInt&,但a+b不能使用,因为a+b是临时的。但它可以用于BigInt const&预期的地方。
https://stackoverflow.com/questions/23307043
复制相似问题