Question:
How to return an array in a class's get function in C++?
Josh
2011-02-16 17:36:03 UTC
I'm trying to write a polynomial application that requires me to utilize classes. Problem is, I have the polynomial stored in two arrays in the class, one for coefficients (float coefficientholder[10]) and one for exponents (int exponentholder[10]), and get functions (at least according to my book) are simply consisting of return commands for use in the main .cpp file.

Since you can't exactly 'return' arrays with the return command, how I am supposed to return the array of coefficients and exponents when I use poly.getcoeff() and poly.getexpn() in the main.cpp file?
Four answers:
Ratchetr
2011-02-16 17:56:13 UTC
The problem is, you have the polynomial stored in two arrays.

That's the problem. Parallel arrays.



What you want to do is return a polynomial, or an array of polynomials. (I'm not clear which).



polynomial seems like a good candidate for a class.

A polynomial HASA coefficient and it HASA exponent.



class polynomial

{

private:

  float coefficient;

  float exponent;

public:

// Constructors and other stuff...

}



Now you can write a function that returns a polynomial or an array of polynomials. Either way, it's 1 return value.



Any time you find yourself using 2 parallel arrays, combine the 2 into 1 class.
Cubbi
2011-02-16 17:49:55 UTC
You can return all other C++ containers. Assuming you wish to keep exponentholder and coefficientholder as arrays, you could return them as vectors:





#include

class Poly

{

     float coefficientholder[10];

     float exponentholder[10];

public:

     std::vector getcoeff() const

     {

         return std::vector(coefficientholder, coefficientholder+10);

     }

};



However, what do you need all ten values for? It seems odd for a polynomial class to expose such details.



Returning a pointer to the first element of each array is also sensible.
?
2016-12-12 17:13:38 UTC
i'm unsure why you will not be able to easily bypass the array. you have got the skill to do: double * function1(int n); double function2(double * arrayEntry); all you will could desire to do is define the size of the double array globally instead of manually putting it to sixteen everywhere, that way the applications become extensible and much less confusing to alter.
James Bond
2011-02-16 17:47:05 UTC
class vector

{

float *c;

int ord;

public:

vector (int sz)

{

c=new float[ord=sz];

}

}



class poly

{

vector A(10);

public:

public vector polycoeff()

{

return A;

}

}

Will it serve?

You can always return pointer to the polynoimial array if you want


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...