好的,我认为这可能只是版本问题,但是我对此并不陌生。我有一个主文件,该文件将重写的<<
运算符用于BigInt
已实现的类:
BigInt a = 3;
cout << a << endl;
cout << (a+a) << endl;
在Visual Studio中,编译器可以很好地理解所有内容,并且运行良好。但是转到Ubuntu 14.04,make
使用我的Makefile(使用简单g++
命令)后,会出现由第三行(以及使用cout和表达式的任何其他行)引起的成千上万个类型错误。如果我删除第三行,它的编译效果很好。第一个错误是:
main.cpp:23:8: error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'BigInt')
cout << (a+a);
^
这很令人困惑,因为我的<<
操作员函数使用了引用参数:
// in BigInt.h, in class' public section:
BigInt operator+(BigInt const& other) const;
friend std::ostream & operator<<(std::ostream& os, BigInt& num);
// in BigInt.cpp:
BigInt BigInt::operator+(BigInt const& other) const {
// call appropriate helper based on signs
if (this->neg == other.neg) {
return sum(other);
}
else {
return difference(other);
}
}
ostream & operator<<(ostream& os, BigInt& num) {
if (num.dataLength == -1) {
os << "**UNDEFINED**";
}
else {
if (num.neg) os << "-";
if (num.dataLength == 0) {
os << "INFINITY";
}
else {
// print each digit
for (int i = num.dataLength - 1; i >= 0; i--) {
os << (short)num.data[i];
}
}
}
return os;
}
那么,为什么第一个cout起作用而第二个却不起作用?有没有可以运行的方法g++
?
ostream & operator<<(ostream& os, BigInt& num)
应该带一个BigInt const& num
。MSVC就此而言不兼容。g ++没有此扩展名。
确保同时更改标题中的声明和BigInt.c
文件中的定义。(此外,通常对.c
包含C
代码.cpp
的文件和包含C++
代码的文件使用。)
原因是(a+a)
创建了一个临时表 BigInt
,该临时表不能绑定到非const
引用。第一个cout
起作用是因为a
它是局部变量,而不是临时变量,因此可以作为常规(非const
)引用传递。
除临时性问题外,应用const
-correctness是一个好习惯:const
除非确实需要更改,否则请进行更改。这可以帮助防止错误。请注意,std::ostream& os
不能为const
,您实际上确实可以通过写入对其进行更改。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句