V
V
Veln2020-08-28 10:01:51
C++ / C#
Veln, 2020-08-28 10:01:51

How to pass an array of objects to a class method, assign each element a value of your choice and return, for example, the sum of its elements?

Hello, I would like to get an answer, at least for the first part of the question
. Here is an example code:

#include <iostream>
#include <string>
using namespace std;
const int n=2;

class xxx{
  private:
    int y;
    
  public:
    void sum(){
      cout<<"Enter y: "; cin>>y;
      switch(y){
        case 1:{
          
          break;
        }
        case 2:{
          
          break;
        }
      }
    }		
};

int main(){
  xxx x[n];
  for(int i=0;i<n;i++){
    x[n].sum();
  }		
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
X
xorknown, 2020-08-28
@xorknown

#include <iostream>
#include <numeric>

constexpr int n = 2;

struct Class {
static int summ (int (&arr)[n] ) {
    return std::accumulate(std::begin(arr), std::end(arr), 0);
}
};

int main() {
    int x[n] = {4,6};
    std::cout << "Summ " << Class::summ(x) << std::endl; 
}

But I advise you to look towards std::vector. It is better not to work with default arrays, especially at the beginning.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question