Reputation: 83
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 !!
Upvotes: 0
Views: 285
Reputation: 122228
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).
Upvotes: 1