Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error while using >> operator overloading

The error looks like this (2nd last line):

Error: no match for 'operator>>' (operand types are 'std::istream' {aka 'std::basic_istream<char>'} and 'Complex()')|

Here is the code:

#include <iostream>

using namespace std;

class Complex {
  private:
    int a, b;
  public:
    Complex(int x, int y) {
        a = x;
        b = y;
    }
    Complex() {
        a = 0;
        b = 0;
    }
    friend ostream& operator << (ostream &dout, Complex &a);
    friend istream& operator >> (istream &din, Complex &a);
};

ostream& operator << (ostream &dout, Complex &a) {
    dout << a.a << " + i" << a.b;
    return (dout);
}

istream& operator >> (istream &din, Complex &b) {
    din >> b.a >> b.b;
    return (din);
}

int main() {
    Complex a();
    cin >> a;
    cout << a;
}
like image 523
Omkar Arora Avatar asked Nov 18 '25 23:11

Omkar Arora


1 Answers

Complex a();

This is a vexing parse. You think it means "default-initialize the variable a, which has type Complex." However, the compiler parses it as "declare a function called a which takes no arguments and returns a Complex value." The syntax is ambiguous: it could mean either, but the language prefers a function declaration to a variable declaration.

Therefore, a is a function, not a variable.

Indeed, there is no declared operator overload that takes a function, which is why you get the error. Note the specific type called out in the error:

operand types are 'std::istream' {aka 'std::basic_istream<char>'} and 'Complex()'
                                                   parens indicate a function ^^

To fix this, replace this line with one of these:

Complex a{}; // C++11 and later only; uniform initialization syntax
Complex a;   // All versions of C++

Neither of these are ambiguous; they can only be parsed as a variable declaration.

like image 129
cdhowie Avatar answered Nov 20 '25 14:11

cdhowie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!