好的,我认为这可能只是一个版本问题,但我是新手。我有一个主文件,它使用我覆盖的 <<
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 有效而第二个 cout 无效?有没有办法运行g++
这样它就可以工作了吗?
最佳答案
ostream & operator<<(ostream& os, BigInt& num)
应该采用 BigInt const& num
。 MSVC is non-compliant with regards to this . g++ 没有这个扩展。
确保更改 header 中的声明和 BigInt.c
文件中的定义。 (此外,对于包含 C
代码的文件通常使用 .c
,对于包含 C++
的文件使用 .cpp
> 代码。)
原因是(a+a)
创建了一个临时 BigInt
,不能绑定(bind)到非const
引用。第一个 cout
起作用是因为 a
是局部变量,而不是临时变量,因此可以作为普通(非 const
)引用传递。
除了临时对象的问题,应用 const
-correctness 是个好习惯: 使事物成为 const
除非你真的需要改变它们。这有助于防止错误。请注意 std::ostream& os
不能是 const
,您确实可以通过写入来更改它。
关于c++ - g++ 编译器为表达式提供 << 类型错误,但在 Visual Studio 中有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34400330/