#include <iostream>
using namespace std;
class Number {
private:
int num;
public:
Number() {
num = 0;
}
Number(int n) {
num = n;
}
// Overload unary + operator
Number operator+() {
return Number(num);
}
void display() {
cout << "Number: " << num << endl;
}
};
int main() {
Number n1(5), n2;
// Call the overloaded unary + operator
n2 = +n1;
n1.display();
n2.display();
return 0;
}
In this program, we define a Number
class that has an int
data member num
. We also define a default constructor and a parameterized constructor to initialize the num
member.
The Number
class overloads the unary +
operator by defining a member function named operator+()
. This operator function returns a Number
object, which is the original object itself. In this case, the overloaded +
operator does not modify the object, but simply returns it.
In the main()
function, we create two Number
objects n1
and n2
. We then call the overloaded +
operator using the syntax +n1
. The result of this operation is assigned to n2
.
Finally, we display the values of n1
and n2
using the display()
member function.
Output:
Number: 5
Number: 5
As we can see, the overloaded +
operator does not modify the object, but simply returns a copy of it. In this case, n2
is a copy of n1
, since the overloaded +
operator returns the original object itself.