简体   繁体   中英

no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}'

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') and Complex . Here is my code.

#include<iostream>
using namespace std;

class Complex {
private:
    int real, imag;
public:
    Complex(int r = 0, int i =0) {real = r; imag = i;}

    // This is automatically called when '+' is used with
    // between two Complex objects
    Complex operator + (Complex const &obj) {
        Complex res;
        res.real = real + obj.real;
        res.imag = imag + obj.imag;
        return res;
    }

    int getR() const { return real; }

    int getC() const { return imag ; }

    ostream& aff(ostream& out)
    {
       out << real << " + i" << imag ;
       return out ;
    }

    void print() { cout << real << " + i" << imag << endl; }
};

Complex operator + (const Complex & a , const Complex &b )
{
    int r = a.getR() + b.getR();
    int c = a.getC() + b.getC();
    Complex x(r , c);
     return x ;
}


ostream& operator<<(ostream& out , Complex& c)
{
   return c.aff(out) ;
}

int main()
{
    Complex c1(10, 5), c2(2, 4);
    cout <<  c1 + c2  << endl ; // An example call to "operator+"
}

Not sure what is wrong with my code, can anyone help?

operator + returns by-value, that means what it returns is a temporary, it can't be bound to lvalue-reference to non-const (ie Complex& ), which is the parameter type of operator<< .

You can change the parameter type to const Complex& ,

ostream& operator<<(ostream& out , const Complex& c)
//                                 ~~~~~
{
   return c.aff(out) ;
}

and you have to make aff a const member function, to make it possible to be called on a const object.

ostream& aff(ostream& out) const
//                         ~~~~~
{
   out << real << " + i" << imag ;
   return out ;
}

Your function is waiting for a lvalue reference, and you try to print c1 + c2 that is a temporary.

You can bind a temporary to a const lvalue reference, so you must wait for a const Complex &c

ostream& operator<<(ostream& out , const Complex& c)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM