I am working on creating a class to handle very large numbers for use in Project Euler challenges. I have overloaded both << and + to work with the class. The following compiles and works properly:
BigNum a(400000000);
BigNum b(400000000);
BigNum c;
c = a + b;
cout << c;
The following produces a compile error:
BigNum a(400000000);
BigNum b(400000000);
cout << (a + b);
The error is: error: no match for ‘operator<<‘ in ‘std::cout << BigNum::operator+(const BigNum&) const(((const BigNum&)((const BigNum*)(& b))))’
For reference, here is the class definition and implementation:
/* BigNum.h */
#include <iostream>
#include <vector>
class BigNum {
public:
BigNum();
BigNum(const BigNum &src);
BigNum(int num);
void print(std::ostream *os);
public:
BigNum &operator=(const BigNum &src);
BigNum &operator+=(const BigNum &src);
const BigNum operator+(const BigNum &src) const;
private:
bool negative;
std::vector<int> digits;
};
std::ostream &operator<<(std::ostream &os, BigNum &bNum);
/* BigNum.cpp */
#include "BigNum.h"
BigNum::BigNum() {
digits.push_back(0);
}
BigNum::BigNum(const BigNum &src) {
digits = src.digits;
}
BigNum::BigNum(int num) {
if(num == 0) {
digits.push_back(0);
}
else {
while(num != 0) {
digits.push_back(num % 10);
num /= 10;
}
}
}
void BigNum::print(std::ostream *os) {
int i;
for(i = digits.size() - 1; i >= 0; i--) {
*os << digits[i];
}
}
std::ostream &operator<<(std::ostream &os, BigNum &bNum) {
bNum.print(&os);
return os;
}
BigNum & BigNum::operator=(const BigNum &src) {
if(this == &src) return *this;
digits = src.digits;
return *this;
}
BigNum & BigNum::operator+=(const BigNum &src) {
int carry, i, k;
carry = 0;
if(digits.size() < src.digits.size()) {
digits.resize(src.digits.size(), 0);
}
{
k = src.digits.size();
for(i = 0; i < k; i++) {
digits[i] += src.digits[i];
digits[i] += carry;
carry = 0;
if(digits[i] > 9) {
carry = 1;
digits[i] -= 10;
}
}
k = digits.size();
for(i = src.digits.size(); i < k; i++) {
digits[i] += carry;
carry = 0;
if(digits[i] > 9) {
carry = 1;
digits[i] -= 10;
}
}
if(carry) {
digits.resize(digits.size() + 1, 1);
}
}
return *this;
}
const BigNum BigNum::operator+(const BigNum &src) const {
BigNum result(*this);
result += src;
return result;
}
Why does
cout << (a + b);
not work? There are obvious work-arounds, but I want to understand why this is happening. I am new to C++, so if there is anything else I am doing incorrectly or could be doing better, please let me know. Thank you.
Your overload of
operator<<doesn’t take theconst BigNumthatoperator+returns. Change the parameter type inoperator<<toconst BigNum &.The function thinks it’s allowed to modify the object passed in, but you’re passing a non-modifiable object, so it doesn’t match.
As pointed out below, the
print()function you call from there needs to beconstas well.