The task is to create 2 variables of the Array class to populate them, output, add and multiply. I created 2 variables of the Array class, after which I wanted to add them, I wrote an addition operator for this, but it does not return an array of sums of the other two arrays
Code:
#include <iostream>
#include <fstream>
#include <string>
void showMenu() {
std::cout << "-------Menu-------" << std::endl <<
"1-Input matrix" << std::endl <<
"2-Print matrix" << std::endl <<
"3-Sum matrix" << std::endl <<
"4-Multiply matrix" << std::endl <<
"0-Exit" << std::endl <<
"------------------" << std::endl;
}
class Array {
public:
Array(const int size) {
this->size = size;
arr = new int[this->size];
}
void fillArr() {
std::cout << "Enter elements of array: ";
for (size_t i = 0; i < size; i++) {
std::cin >> arr[i];
}
}
int getSize() {
return size;
}
int& operator [] (const int index) {
return arr[index];
}
void showArr() {
for (size_t i = 0; i < size; i++) {
std::cout << arr[i] << '\t';
}
std::cout << std::endl;
}
~Array() {
delete[] arr;
}
private:
int size = 0;
int* arr;
};
Array operator + (Array arr1, Array arr2) {
int temp = 0;
if (arr1.getSize() < arr2.getSize())
temp = arr1.getSize();
else temp = arr2.getSize();
Array tempArr(temp);
for (size_t i = 0; i < temp; ++i) {
tempArr[i] = arr1[i] + arr2[i];
}
tempArr.showArr();
return tempArr;
}
Array operator * (Array arr1, Array arr2) {
int temp = 0;
if (arr1.getSize() < arr2.getSize())
temp = arr1.getSize();
else temp = arr2.getSize();
Array tempArr(temp);
for (size_t i = 0; i < temp; ++i) {
tempArr[i] = arr1[i] * arr2[i];
}
return tempArr;
}
std::int16_t main() {
int num = 0;
int size1 = 0, size2 = 0;
std::cout << "Enter size of first array: ";
std::cin >> size1;
std::cout << "Enter size of second array: ";
std::cin >> size2;
Array arr1(size1), arr2(size2);
while (true) {
showMenu();
std::cout << "Choice: ";
std::cin >> num;
switch (num) {
case 1:
arr1.fillArr();
arr2.fillArr();
break;
case 2:
arr1.showArr();
arr2.showArr();
break;
case 3: {
Array temp(arr1 + arr2);
temp.showArr();
break;
}
case 4:
(arr1 * arr2).showArr();
break;
}
}
}
I tried to change the array and the operator itself, but nothing came out. Help understand the problem