C++ Nat类运算符重载编译报错:invalid operands to binary expression问题求助
Let's break down what's causing your compiler error and fix it step by step:
Root Cause of the Error
The error pops up because your overloaded operator<< takes a non-const reference (Nat &n) as its second parameter:
ostream& operator << (ostream &out, Nat &n) { ... }
In your main function, you’re trying to output the results of a + b and (a ^ b)—these are temporary Nat objects (since both operator+ and operator^ return by value). C++ doesn’t allow binding temporary objects to non-const lvalue references, which is why the compiler rejects this code.
Quick Fix for the Output Operator
Change the second parameter to a const Nat &n (const reference). This works because const references can bind to temporary objects, and your ival() method is already marked as const (great practice for read-only operations):
ostream& operator << (ostream &out, const Nat &n) { return out << n.ival(); // Removed the extra `endl` here—your main already adds one, so this avoids double newlines }
Additional Issues to Fix
While we’re at it, let’s clean up other potential problems in your code:
Broken
operator^Logic
It looks like you’re trying to implement the Euclidean algorithm for GCD, but your recursive step is backwards. Right now, it will return incorrect results for most cases. Fix it to use the correct order of operands:Nat operator ^(const Nat &n, const Nat &m) { if (n.ival() == 0) return m; Nat rem(m.ival() % n.ival()); return rem ^ n; // Swap to use the remainder and original divisor for recursion }Redundant Member Variables
YourNatclass hasbandGmembers that are never used or initialized. Delete them to avoid confusion and unnecessary memory usage:class Nat { int a; // Only keep the used member public: // ... rest of your class code ... };Const-Correct
operator+=
Sinceoperator+=only reads from the inputm(doesn’t modify it), make its parameter a const reference:Nat operator +=(const Nat &m) { a += m.a; return *this; }
Full Corrected Code
Here's the revised code with all fixes applied:
#include <iostream> using namespace std; class Nat { int a; public: Nat(int n) : a(n) {} // Use member initializer list for cleaner initialization Nat operator +=(const 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 ^ n; } ostream& operator << (ostream &out, const Nat &n) { return out << n.ival(); } 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; }
This code should compile without errors and correctly compute the sum and GCD of your Nat objects.
内容的提问来源于stack exchange,提问作者차현대

