In: Computer Science
Write this program in C++
You are given a source file in your work area for this assignment.
It consists of a declaration for a Val node. There are declarations for three overloaded operator functions, which you must fill in: operator+, operator*, and operator!.
operator+ should implement addition. operator* should implement multiplication.
operator! should reverse the digits of its operand (i.e., of "this") and return the reversed integer. So for example !123 should return 321.
It should be straightforward to reverse an integer. You can extract the least significant digit by using % 10. You can remove the least significant digit by dividing by 10. Other approaches are possible as well.
These operator functions should not be a lot of code. The addition and multiplication can be written in 1-2 lines, and the reverse function within about 10 lines.
Source Code:
#include
using namespace std;
class Val {
int v;
public:
Val(int v=0) : v(v) {}
friend ostream& operator<<(ostream&
out, const Val& v) {
out << v.v;
return out;
}
Val operator+(const Val& o) const {
// FILL IN
}
Val operator*(const Val& o) const {
// FILL IN
}
Val operator!() const {
// FILL IN
}
};
int main()
{
Val values[] = { 2, 44, 19, 4391 };
const int nv = sizeof(values)/sizeof(values[0]);
for( int i=0; i<nv; i++ ) {
cout << values[i] <<
endl;
cout << "!" <<
values[i] << " == " << !values[i] << endl;
for( int j = i+1; j < nv; j++
) {
cout <<
values[j] << endl;
cout <<
values[i] << " + " << values[j] << " == "
<< values[i] + values[j] <<
endl;
cout <<
values[i] << " * " << values[j] << " == "
<< values[i] * values[j] <<
endl;
}
}
return 0;
}
#include<iostream>
using namespace std;
class Val {
int v;
public:
Val(int v=0) : v(v) {}
friend ostream& operator<<(ostream& out,
const Val& v) {
out << v.v;
return out;
}
Val operator+(const Val& o) const {
// FILL IN
Val temp; // create new
variable
temp.v = o.v + this->v; //
assign value to it
return temp; // return
}
Val operator*(const Val& o) const {
// FILL IN
Val temp;
temp.v = o.v *
this->v;
return temp;
}
Val operator!() const {
// FILL IN
Val temp; // create new variable
int r,rev = 0;
int num = v; // create dup of
this->v
while(num > 0){ // reverse
r = num %
10;
rev = rev*10 +
r;
num = num/10;
}
temp.v = rev; // assign reverse to
v
return temp;
}
};
int main()
{
Val values[] = { 2, 44, 19, 4391 };
const int nv = sizeof(values)/sizeof(values[0]);
for( int i=0; i<nv; i++ ) {
cout << values[i] << endl;
cout << "!" << values[i] << " == " <<
!values[i] << endl;
for( int j = i+1; j < nv; j++ ) {
cout << values[j] << endl;
cout << values[i] << " + " << values[j] <<
" == "
<< values[i] + values[j] << endl;
cout << values[i] << " * " << values[j] <<
" == "
<< values[i] * values[j] << endl;
}
}
return 0;
}
/* OUTPUT */
/* PLEASE UPVOTE */