Search code examples
c++operator-overloadingoverloadingistream

Error: No match for 'operator>>' Overloading istream operator


learning C++ right now and ran into a bit of a problem. While trying to complete an example and make sure it works ran into the error:

error: no match for 'operator>>' (operand types are 'std::istream' and 'const int') conversion of argument 1 would be ill-formed

Here is my code,

#include <iostream>
#include <sstream>
#include <cstdlib>
using namespace std;

class Distance {
    private:
        int feet;
        int inches;
    public:
        Distance() {
            feet = 0;
            inches = 0;
        }
        Distance(int f, int i) {
            feet = f;
            inches = i;
        }
        friend ostream &operator<<( ostream &output, const Distance &D ) {
            output << D.feet << "\'" << D.inches << "\"" << endl;
            return output;
        }
        friend istream &operator>>( istream &input, const Distance &D ) {
            input >> D.feet >> D.inches;
            return input;
        }
}; 

int main() {
    Distance D1(11,10), D2(5,11), D3;
    cin >> D3;
    cout << "First Distance : " << D1 << endl;
    cout << "Second Distance : " << D2 << endl;
    cout << "Third Distance : " << D3 << endl;
    return 0;
}

Trying to overload the istream and ostream operators, but running into problems with the istream operator >>.

First thought to convert the variable D.feet and D.inches to char* but that doesn't seem right considering that I have to feed an int into the variables. Not sure what is wrong with my code, can anyone help?


Solution

  • Remove const in >> operator overload.

    Your Distance is const'd.