简体   繁体   中英

invalid operands to binary expression ('std::__1::ostream' (aka 'basic_ostream<char>') and class

I think I did all things clear. I used operator overloading concerned with "cout" and " cin" and "^" and "+" about Nat class. I don't know why my compiler doesnt understand my code. It must be a problem in making operator overloading but i dont know why...
enter code here

#include <iostream>

using namespace std;

  class Nat
{
int a;
int b;
int G;
public:
Nat(int n)
{
a = n;
}

Nat operator +=(Nat &m)
{
a += m.a;
return *this;
}

int ival() const
{
    return a;
}

void set_ival(int i)
{
    a = i;
}
};


Nat operator +(const Nat &n, const Nat &m)
{
    Nat k(n.ival() + m.ival());
    return k;
}

Nat operator ^(const Nat &n, const Nat &m)
{
    if (n.ival() == 0)
        return m;
    Nat rem = m.ival() % n.ival();
    return rem ^ m;
}

ostream& operator << (ostream &out, Nat &n)
{
return out << n.ival() << endl;
}

istream& operator >> (istream& in, Nat &n)
{
    int i = 0;
    in >> i;
    n.set_ival(i);
    return in;
}

int main()
{
    Nat a(0), b(0);
    cin >> a >> b;
    cout << a + b << " " << (a ^ b) << endl;
}

my compiler shows this error !!

在此处输入图像描述

The output operator is not modifying the object, hence the parameter should be const& .

To fix your code, change:

ostream& operator<<(ostream& out,const Nat& n) {                                 
                                 // ^^^-------------- !!!
    return out << n.ival() << endl;
}

The complete error message should contain a part that says:

error: cannot bind non-const lvalue reference of type 'Nat&' to an rvalue of type 'Nat'

And thats the reason for your error. a + b is a rvalue that you cannot bind to a non-const lvalue reference. It just doesn't make sense to get a reference to a + b (and be able to modify the value via that reference).

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