Calculator Class Question

I've been playing around with C++ for several years off and on in different areas. For the last year or so I've been using the SDL2 library and doing mostly game stuff.

That being said tonight I decided to go back to some basics to cover some of the stuff I never fully understood. And that bring me to this question.

I am writing a calculator class to do basic add, subtract, divide, multiply operations. I created a "Calculator" class and started making my first method "add" This method will take as many numbers as the user wants, then output the value of them all added up.

If I do just int add(int a, int b) then the function will only be able to input 2 numbers to add. How would I create this so that the user could input as many numbers as he wanted and have the function take all the numbers?
Well, I guess you could use an array (or better vector) to hold all the numbers, and then have a function to sum the contents of the vector.
Not sure I understand what you're saying.
I guess Chervil meant sth. like this.
1
2
3
4
5
6
class Calculator
{
public:
  // returns the sum of the numbers in the vector numbers
  int Add(const vector<int> &numbers);
};
You can use an initializer list or variadic templates, the latter being more of my personal preference:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>//Initializer list 
#include <initializer_list>
#include <algorithm>
using namespace std;
template <typename T>
T addition(initializer_list<T>  l)
{
    return accumulate(l.begin(), l.end(), 0);
}

int main()
{
    cout << addition ({5, 6, 7});
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>//Variadic template
using namespace std;

template<typename T>
T addition (T v) {
  return v;
}

template<typename T, typename... Args>
T addition (T first, Args... args) {
  return first + addition (args...);
}

int main()
{
    cout << addition ( 5, 6, 7);
}
I guess Chervil meant sth. like this.

Approximately yes.

However, I think there is a clear difference in usage between

add
a + b =

and

sum
a1 + a2 + a3 + .... + an-2 + an-1 + an

Hence I would have separate functions for add and sum, since their usage is different.

Where I'm not so sure is how the user would interact with such a program - what sort of input would they give, in order to invoke each operation?

For example, if the input was to be something like
2 + 3 + 7 + 13 + 17

then there is no need to add more than a pair of values at a time, but rather there is a need to interpret and evaluate the expression.
I would make a post fix notation calculator rather than having different methods for each operation.
Topic archived. No new replies allowed.