Answer to Question #113022 in C++ for joya

Question #113022
Create a class that allows you to treat the 10 separate arrays in Exercise 10 as a single
one-dimensional array, using array notation with a single index. That is, statements in
main() can access their elements using expressions like a[j], even though the class
member functions must access the data using the two-step approach. Overload the subscript
operator [] (see Chapter 9, “Inheritance”) to achieve this result. Fill the arrays
with test data and then display it. Although array notation is used in the class interface in
main() to access “array” elements, you should use only pointer notation for all the operations
in the implementation (within the class member functions).
1
Expert's answer
2020-04-30T13:38:29-0400
#include <cstdlib>
#include <iostream>


using namespace std;


class Arr10 {


public:
	static const size_t 	TOTAL_ARRAYS = 10;
	Arr10(size_t _size);
	~Arr10();
	int& operator[](int);
	void print() const;
private:
	int * 				arr[TOTAL_ARRAYS];
	size_t 				size;
};


int& Arr10::operator[](int index)
{
	if (static_cast<size_t>(index) >= size * TOTAL_ARRAYS) {
		return arr[0][0];
	}
	size_t x = index / size;
	size_t y = index % size;
	return arr[x][y];
}


Arr10::Arr10(size_t _size)
{
	size = _size;


	if (size != 0) {
		for (int i = 0; i < static_cast<int>(TOTAL_ARRAYS); ++i) {
			arr[i] = new int[size];
			for (int j = 0; j < static_cast<int>(size); ++j) {
				arr[i][j] = 0;
			}
		}
	}
}


Arr10::~Arr10()
{
	for (int i = 0; i < static_cast<int>(TOTAL_ARRAYS); ++i) {
		for (int j = 0; j < static_cast<int>(size); ++j) {
			delete arr[i];
		}
	}
}


void Arr10::print() const
{
	for (int i = 0; i < static_cast<int>(TOTAL_ARRAYS); ++i) {
		for (int j = 0; j < static_cast<int>(size); ++j) {
			cout << arr[i][j] << " ";
		}
		cout << endl;
	}




}


int main()
{
	size_t s = 4;
	Arr10 arr10(s);
	for (int i = 0; i < static_cast<int>(s * Arr10::TOTAL_ARRAYS); ++i)
		arr10[i] = i;


	arr10.print();


	arr10[0] = 66;
	arr10[4] = 66;
	arr10[8] = 66;
	arr10[33333] = 66;
	cout << endl;
	arr10.print();
	return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS