Assume the existance of a class Accumulator defined below. Write an operator fun
ID: 3798433 • Letter: A
Question
Assume the existance of a class Accumulator defined below. Write an operator function for this class using the + operator which does the same operation as the add function as defined in exercise 11180, so that if a is an Accumulator object we can increase a by three using either a.add(3) or a + 3.
Accumulator ploblem below with answer
Write a full class definition for a class named Accumulator, and containing the following members:
A data member named sum of type integer .
A constructor that accepts no parameters . The constructor initializes the data member sum to 0.
A member function named getSum that accepts no parameters and returns an integer . getSum returns the value of sum .
A member function named add that accepts an integer parameter and returns no value . add increases the value of sum by the value of the parameter .
Explanation / Answer
#include <iostream>
using namespace std;
class Accumulator{
private:
int sum;
public:
Accumulator();
int getSum();
int operator+(int someNum); //operator overloading function
};
Accumulator::Accumulator(){
sum=0;
}
int Accumulator::getSum (){
return sum;
}
int Accumulator::operator+(int someNum){
sum=sum +someNum;
return sum;
}
int main()
{
Accumulator ac; //accumulator object
cout<<ac+3; //adding 3 to object
return 0;
}
output:
3
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.