When declaring a function that works on a table of class instances, how can I declare a variable e.g. double length

from the next element in the table, so that when the function is working on the current element in the table, it can access the value of a member variable in the next element. For example, adding the lengths of array[1] and array[i+1]for up to 10 elements.

from the next element in the table, so that when the function is working on the current element in the table, it can access the value of a member variable in the next element. For example, adding the lengths of array[1] and array[i+1]for up to 10 elements.

Say you declare

Class element

{

double length;

public:

double total_length(int number_of_element);

};

double element::total_length(int number_of_element)

{

double sum_length = 0;

for (int i = 0; i < number_of_element; i++)

sum_length += this[i].length;

return sum_length;

}

But be careful - you must make sure there are number_of_element elements in an array.

Say you declare

Class element

{

double length;

public:

double total_length(int number_of_element);

};

double element::total_length(int number_of_element)

{

double sum_length = 0;

for (int i = 0; i < number_of_element; i++)

sum_length += this[i].length;

return sum_length;

}

void main(void)

{

element array[5];

// ...

// Print out the total length.

cout << array[0].total_length(5) << end;

}

Please provide your email to receive a free trial preview!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.