Instinct
Instinct

Reputation: 2251

I need to create an array of a user define class and each element in the array has a member function containing different inputs/outputs

For example,

Class myMath (){ int doMath(int x, int y)}

main()
  {
     myMath math[5];

     math[0].doMath(10,20);     //this will add x and y
     math[1].doMath(3,1);       //this will subtract x and y
     etc...
  }

How can this be done? I am a beginner at c++ so please explain in detail :P Thank you.

Upvotes: 1

Views: 89

Answers (1)

jogojapan
jogojapan

Reputation: 69977

(This answer assumes the C++11 standard for C++.)

As indicated in your comment, we can assume that all operations stored in the array will be taking two integer arguments and returning an integer. It is therefore possible to represent them as functors of this data type:

std::function<int(int,int)>

A fixed-size, 5-element array of that data type is best implemented as

std::array<std::function<int(int,int)>,5>

The below is a complete example that makes use of these data types. It implements the four basic operations add, subtract, multiply and divide using the function objects provided by the standard library (std::plus<int>, std::minus<int> etc.). There is also a fifth arithmetic operation for which I use an ad-hoc implementation of power over integers. It is implemented as a lambda function (a new type for anonymous functions provided by C++11. It can be converted to std::function<int(int,int)> and stored in the array as well.

#include <iostream>
#include <functional>
#include <array>

int main()
{
  /* Customized arithmetic operation. Calculates the arg2-th
     power of arg-1. */
  auto power = [](int arg1, int arg2) {
    int result = 1;
    for (int i = 0 ; i < arg2 ; ++i)
      result *= arg1;
    return result;
  };

  /* Fixed-size array of length 4. Each entry represents one
     arithmetic operation. */
  std::array<std::function<int(int,int)>,5> ops {{
      std::plus<int>(),
      std::minus<int>(),
      std::multiplies<int>(),
      std::divides<int>(),
      power
  }};

  /* 10 + 20: */
  std::cout << ops[0](10,20) << std::endl;
  /* 3 - 1: */
  std::cout << ops[1](3,1) << std::endl;
  /* 3rd power of 9: */
  std::cout << ops[4](9,3) << std::endl;

  return 0;
}

Upvotes: 1

Related Questions