ves*_*len 4 c++ cout operator-overloading c++11 visual-studio-2012
好吧,我认为这可能只是版本问题,但我是新手.我有一个主文件,它使用我重写的<<运算符为BigInt我实现的类:
BigInt a = 3;
cout << a << endl;
cout << (a+a) << endl;
Run Code Online (Sandbox Code Playgroud)
在Visual Studio中,编译器可以很好地理解所有内容并且运行良好.但转移到Ubuntu 14.04,make使用我的Makefile(使用普通g++命令)给我带来了由第三行(以及任何其他将cout与表达式一起使用的行)引起的bazillion类型错误.如果我删除第三行,它编译很好.第一个错误是:
main.cpp:23:8: error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'BigInt')
cout << (a+a);
^
Run Code Online (Sandbox Code Playgroud)
这很令人困惑,因为我的<<操作符函数需要引用参数:
// 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;
}
Run Code Online (Sandbox Code Playgroud)
那么为什么第一个cout工作但不是第二个?有没有办法运行g++,它可以工作?
BoB*_*ish 13
ostream & operator<<(ostream& os, BigInt& num)
Run Code Online (Sandbox Code Playgroud)
应该拿一个BigInt const& num.MSVC对此不符合要求.g ++没有此扩展名.
确保更改标题中的声明和BigInt.c文件中的定义.(另外,这是正常的使用.c为包含文件C的代码,和.cpp用于包含文件C++的代码.)
原因是(a+a)创建一个临时的 BigInt,不能绑定到非const引用.第一个cout工作因为a是局部变量,而不是临时变量,因此可以作为普通(非const)引用传递.
除了临时问题之外,最好是应用 - const正确性:const除非你真的需要改变它们.这有助于防止错误.注意std::ostream& os不能const,你真的通过写它来改变它.
问题在于
friend std::ostream & operator<<(std::ostream& os, BigInt& num);
Run Code Online (Sandbox Code Playgroud)
因为你拿BigInt& num这个不会起作用,(a+a)因为crate是临时的,你不能参考一个临时的.它适用于MSVS,因为它们有一个扩展允许这个,但g ++没有.将其更改为
friend std::ostream & operator<<(std::ostream& os, const BigInt& num);
Run Code Online (Sandbox Code Playgroud)
那么为什么第一个cout工作但不是第二个?
你operator <<通过非const引用得到它的第二个参数.像临时工一样(a+a)无法绑定,所以第二次通话是非法的.MSVC允许它作为扩展,但它不是标准的C++.
有没有办法运行g ++这样它可以工作?
不.修改您的操作员使用const引用.
| 归档时间: |
|
| 查看次数: |
191 次 |
| 最近记录: |