Berk Olcay
Berk Olcay

Reputation: 161

operator overloading ">>" error

I'm trying to overload >> operator. I wrote the code below for overload and trying to use it in the main. I have "no operator ">>" matches these operands" and c2679 errors. I looked through the internet but couldn't find a solution.

Here is my operator overload.

friend istream& operator >> (istream &in, Polynomial &polynomial) 

{

    in >> polynomial.e;
    if (polynomial.e > 20)
        throw "Bad Input!";

    polynomial.x = new double[polynomial.e];
    for (int i = 0; i < polynomial.e; i++) {
        polynomial.x[i] = 0;
        in >> polynomial.x[i];
    }

    return in;
}

and tryingto use it with this code in main.

out << "poly 1" << endl;
Polynomial *newPol1 = new Polynomial();
try {
    cin >> newPol1;
}

catch (char* s)
{
    cout << s << endl;
}

Thank you

Upvotes: 0

Views: 56

Answers (2)

Loki Astari
Loki Astari

Reputation: 264331

No need for the new:

Polynomial newPol1;
try {
    std::cin >> newPol1;
}
...

Or if you really do want to use dynamically allocated object then de-reference it.

Polynomial *newPol1 = new Polynomial();
try {
    std::cin >> (*newPol1);  // notice the *
}
...

Some other things to note.

if (polynomial.e > 20)   // If things go bad.
                         // in a stream it is  more normal 
    throw "Bad Input!";  // to set the bad bit on the stream.
                         // You can set the stream to throw an
                         // exception if required.

So I would have expected:

if (polynomial.e > 20) {
    in.setstate(std::iosbase::failbit);
}

Then usage is:

if (std::cin >> newPol1) {
    // it worked
}
else {
    // it failed
}

Upvotes: 1

sjrowlinson
sjrowlinson

Reputation: 3355

You are trying to use std::cin on a pointer to type Polynomial here, if you must use pointers then change

std::cin >> newPol1;

to

std::cin >> (*newPol1);  // dereference pointer

It would be better to not use pointers though and just do,

Polynomial newPol1;
std::cin >> newPol1;

Upvotes: 2

Related Questions